美文网首页
Reverse Integer

Reverse Integer

作者: 瞬铭 | 来源:发表于2019-02-22 11:35 被阅读0次
    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

          本文链接:https://www.haomeiwen.com/subject/ksgsyqtx.html