Loading

7. [栈]整数反转

7. 整数反转

利用循环和数学运算的方式进行整数反转,这个思路类似于模拟\(x\)出栈的过程:

\(while \ loop(x != 0):\)

\(pop = x\%10\)

\(res = res * 10 + pop\)

\(x = x / 10\)

由于题目将反转后的数字限制在\([Integer.MIN\_VALUE, \ Integer.MAX\_VALUE]\)的范围里,因为long数据类型是64位有符号的java原始数据类型,我们可以使用long初始化反转结果,反转完成后与Integer.MIN_VALUEInteger.MAX_VALUE比较即可输出答案。

// 执行耗时:1 ms,击败了100.00% 的Java用户
// 内存消耗:35.9 MB,击败了94.83% 的Java用户

class Solution {
    public int reverse(int x) {
        long res = 0;
        while (x != 0) {
            res = res * 10 + x % 10;
            x /= 10;
        }
        if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE){
            return 0;
        }
        return (int)res;
    }
}
posted @ 2020-10-21 22:41  上海井盖王  阅读(87)  评论(0)    收藏  举报