Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Example2: x = -123, return -321
"越是简单的题目越要注意细节,一般来说整数的处理问题要注意的有两点,一点是符号,另一点是整数越界问题。"这道题比较简单 但是简单题就是考细节. 注意Integer.MIN_VALUE的绝对值是比Integer.MAX_VALUE大1的,所以经常要单独处理.
public class Solution {
public int reverse(int x) {
if (x == Integer.MIN_VALUE) {
return 0;
}
int num = Math.abs(x);
int res = 0;
while (num != 0) {
if (res > (Integer.MAX_VALUE - num % 10) / 10) {
return 0;
}//防止res溢出
res = res * 10 + num % 10;
num /= 10;
}
if (x > 0) {
return res;
} else {
return -res;
}
}
}
没有评论:
发表评论