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
Note:
Assume we are dealing with an environment which could only store
integers within the 32-bit signed integer range: [−231, 231 − 1]. For
the purpose of this problem, assume that your function returns 0 when
the reversed integer overflows.
常规问题,利用取余和除法从后往前一个个进行,注意边界即可
class Solution {
public int reverse(int x) {
if (0 == x) return 0;
int preRes = 0; //上一步的结果
int res = 0; //当前结果
int mod = 0; //余数
while (x != 0){
preRes = res;
mod = x % 10;
res = res*10 + mod;
x /= 10;
if ((res-mod)/10 != preRes) //判断边界
return 0;
}
return res;
}
}