Reverse Integer is similar with the Palindrome Number
1. negative or positive
2. avoid overflow
public int reverse(int x) {
//negative and positive
boolean negative = (x > 0) ? false : true;
int temp = Math.abs(x);
long result = 0;
while (temp > 0) {
result = result * 10 + temp%10;
temp /= 10;
}
if (result > Integer.MAX_VALUE) {
return 0;
}
if (negative) return 0-(int)result;
return (int)result;
}
No comments:
Post a Comment