题目
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例
输入: 123
输出: 321
输入: -123
输出: -321
输入: 120
输出: 21
思路
用%
取最后一位,用/
取除最后一位前面的,依次取出。再配合边界判断。
//pop operation:
pop = x % 10;
x /= 10;
//push operation:
temp = rev * 10 + pop;
rev = temp;
代码
class Solution {
public int reverse(int x) {
int sum = 0;
while (Math.abs(x) != 0) {
if(Math.abs(sum) > Integer.MAX_VALUE / 10) {
return 0;
}
sum = sum * 10 + x % 10;
x = x / 10;
}
return sum;
}
}