diff --git a/java/007_Reverse_Integer.java b/java/007_Reverse_Integer.java index c6607a9..7ec569c 100644 --- a/java/007_Reverse_Integer.java +++ b/java/007_Reverse_Integer.java @@ -1,13 +1,13 @@ class Solution { public int reverse(int x) { - if (x == 0) return 0; - long res = 0; + int rev = 0; while (x != 0) { - res = res * 10 + x % 10; - if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) - return 0; + int pop = x % 10; x /= 10; + if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0; + if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0; + rev = rev * 10 + pop; } - return (int) res; + return rev; } } \ No newline at end of file