# LeetCode Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

res * 10 + posx % 10 > Integer.MAX_VALUE

res > (Integer.MAX_VALUE - posx % 10) / 10

AC Code

public class Solution {
public int reverse(int x) {
//1259
if(x == Integer.MIN_VALUE){
return 0;//Integer.MIN_VALUE is -2^31, the abs of which is larger than Integer.MAX_VALUE(2^31 - 1)
}
int posx = Math.abs(x);
int res = 0;
while(posx != 0){
int rem = posx % 10;
//see whether res * 10 + posx % 10 > Integer.MAX_VALUE if yes, overflow
//note that we move the item except res in the right to the left
if(res > (Integer.MAX_VALUE - rem) / 10){
return 0;
}
res = res * 10 + rem;
posx /= 10;
}
return x>0?res:-res;
}
}

posted @ 2018-04-23 08:01  llguanli  阅读(90)  评论(0编辑  收藏  举报