Reverse Integer
Table of contents
Problem
Given a signed 32-bit integer x
, return x
with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1]
, then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Input: x = 123
Output: 321
Input: x = -123
Output: -321
Input: x = 120
Output: 21
Explanation
Everything else is pretty straightforward, but the tricky part is checking for overflow.
Because of the assumption, we cannot use a long
to store the reversed integer, and then check if it is within the range of a 32-bit integer.
So I decided to store the reversed integer as a string, and then if we fail to parse it as an integer, we know it is out of range.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int reverse(int x) {
int sign = (x < 0) ? -1 : 1;
x = sign * x;
StringBuilder sb = new StringBuilder();
while (x > 0) {
sb.append(x % 10);
x /= 10;
}
try {
return sign * Integer.parseInt(sb.toString());
} catch (NumberFormatException e) {
return 0;
}
}
The complexity is $O(\log x)$.