Math
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public int reverse(int x) { int res = 0; boolean positive = x >= 0; while (x != 0) { int digit = x % 10; x /= 10; if (positive) { if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && digit > 7)) { return 0; } } else { if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && digit == -9)) { return 0; } } res = res * 10 + digit; }
return res; } }
|
Math
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public int reverse(int x) { int res = 0; while (x != 0) { if (res < Integer.MIN_VALUE / 10 || res > Integer.MAX_VALUE / 10) { return 0; }
int digit = x % 10; x /= 10; res = res * 10 + digit; }
return res; } }
|
正负数可以合并处理,同时输入值为 int 类型时最高位最大值为 2 可以省去部分临界值判断。
References
7. Reverse Integer