'Why 1534236469 can't pass [closed]
I think 1534236469 out of range! Leetcode: 7. Reverse Integer I can't pass the test input 1534236469. why? the return range is[Integer.MAX_VALUE, Integer.MIN_VALUE],others should return zero
class Solution {
public int reverse(int x) {
if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE)
return 0;
int ans = 0;
while(x != 0) {
ans = ans * 10 + (x % 10);
x /= 10;
}
return ans;
}
}
Thank for your help
Solution 1:[1]
The reverse of 1534236469
is 9646324351
, which is larger than Integer.MAX_VALUE
, so your code will result in numeric overflow and an incorrect result.
You can use long
instead of int
to fix the problem.
EDIT:
Your added if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE)
condition is pointless, since x
is int
, so it will never be outside the valid range of int
s.
Even if x
is within the valid range, the reverse of x
may be outside the range. If you want to detect that the reversed x
is too large and return 0, you should use long
internally:
class Solution {
public int reverse(int x) {
long ans = 0;
while(x != 0) {
ans = ans * 10 + (x % 10);
x /= 10;
}
if(ans > Integer.MAX_VALUE || ans < Integer.MIN_VALUE) {
return 0;
} else {
return (int) ans;
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dr.jacky |