How to reverse integer in php

藏色散人
Release: 2023-03-14 07:48:02
Original
2391 people have browsed it

php method to implement integer reversal: 1. Create a PHP sample file; 2. Use the "function reverse($x) {...}" method to achieve integer reversal.

How to reverse integer in php

#The operating environment of this article: Windows7 system, PHP7.1, Dell G3.

How to achieve integer reversal in php?

PHP algorithm integer reversal

Given a 32-bit signed integer, you need to reverse the digits on each bit of this integer. change.

Example 1:

Input: 123

Output: 321

Example 2:

Input: -123

Output: -321

Example 3:

Input: 120

Output: 21

Note:

Assume our The environment can only store 32-bit signed integers, so its value range is [−231, 231 − 1]. Please follow this assumption and return 0 if the integer overflows after inversion.

class Solution {
    /**
     * @param Integer $x
     * @return Integer
     */
    function reverse($x) {
 
        $max = pow(2,31)-1;
        $min = pow(-2,31);
        $strlen = strlen($x);
        if($x >=0){
            $num = (int)strrev($x);
        }else{
            $num = '-'.(int)strrev(trim($x,'-'));
        }
        if($min  < $num && $num < $max){
            return $num;
        }else{
            return 0;
        }
    }
}
Copy after login

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to reverse integer in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!