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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
思路:
刚开始没有仔细审题,没注意到溢出返回0。如果溢出则temp去掉最后一位的数跟上一次保存的ans肯定不一样,以此判断是否溢出。
class Solution {
public int reverse(int x) {
boolean neg = false;
if(x < 0) {
neg = true;
x = -x;
}
int ans = 0, temp = 0;
while(x > 0) {
int tail = x%10;
temp = temp*10 + tail;
if((temp - tail)/10 != ans) return 0;
ans = temp;
x/=10;
}
if(neg) return -ans;
else return ans;
}
}