- Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example
Note
Consideration
- In Java, the integer is also 32 bits, ranging from -2,147,483,648 to +2,147,483,647.
- if x is positive, if rev exceeds the range, then either rev > max/10 or (rev=max/10 and pop > max %10)
- if x is negative, the situation is similar.
Solution 1
Time Complexity: O(log(x)). There are roughly log_{10}(x) digits in x.
Space Complexity: O(1)
==class Solution {
public int reverse(int x) {
int rev = 0;
while(x != 0) {
int pop = x % 10;
// check positve overflow
if(rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE/10 && pop > Integer.MAX_VALUE%10 ))
return 0;
// check negative overflow
if(rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE/10 && pop < Integer.MIN_VALUE%10))
return 0;
rev = rev*10+pop;
x = x/10;
}
return rev;
}
}
Solution 2
class Solution {
public int reverse(int x) {
long rev = 0;
while(x != 0) {
int pop = x % 10;
rev = rev*10+pop;
x = x/10;
}
if(rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE)
return 0;
return (int)rev;
}
}