Home  >  Article  >  Backend Development  >  How to reverse integer in php

How to reverse integer in php

藏色散人
藏色散人Original
2021-11-29 11:31:482400browse

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;
        }
    }
}

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!

Statement:
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
Previous article:What does php vc15 mean?Next article:What does php vc15 mean?