Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21

int reserve

除数模

class Solution {

    /**
     * @param Integer $x
     * @return Integer
     */
    function reverse($x) {
        $y   = $x > 0 ? $x : (-1) * $x;
        $arr = array();
        $res = 0;
        while ($y) {
            $num   = $y % 10;
            $y     = intval($y / 10);
            $arr[] = $num;
        }
        $count = count($arr) - 1;
        foreach ($arr as $k => $v) {
            $res += $v * pow(10, ($count - $k));
        }
        if($res > 2147483647){
            $res = 0;
        }
        $res = $x > 0 ? $res : (-1) * $res;
        return $res;
    }
}


$class = new Solution();
$res   = $class->reverse(123);
var_dump($res);

你可能感兴趣的:(Reverse Integer)