[LeetCode] 007.Reverse Integer (
2017-08-22 本文已影响0人
QyQiaoo
Problem description
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Code
class Solution {
public int re(int x) {
int res = 0;
while(x != 0) {
if((res * 10 + x % 10) / 10 != res) {
return 0;
}
res = res * 10 + x % 10;
x /= 10;
}
return res;
}
public int reverse(int x) {
if(x > 0) {
return re(x);
} else {
return 0 - re(0 - x);
}
}
}
Analysis
- 溢出判断