Reverse Integer
题目描述:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
code(c++):
法一:
int reverse(int x) {
int max = (numeric_limits<int>::max)();
int min = (numeric_limits<int>::min)();
if(x >= -9 && x <= 9)
return x;
if(x == max || x == min)
return 0;
int sign = x >= 0 ? 1 : -1;
int temp = sign == 1 ? x : -x;
int count = 0;
while(temp > 9){
++count;
temp /= 10;
}
long powNum = 10;
long ans = 0;
for(; count >= 0; --count){
ans += x % powNum / (powNum / 10) *
pow(10, count);
powNum *= 10;
}
if(ans >= max || ans <= min)
return 0;
return ans;
}
法二:
int reverse2(int x) {
int max = (numeric_limits<int>::max)();
int min = (numeric_limits<int>::min)();
if (x == max || x == min)
return 0;
long ans = 0;
while (x != 0){
ans = ans * 10 + x % 10;
x /= 10;
}
if (ans >= max || ans <= min)
return 0;
return ans;
}
note:
- int型的上下边界问题要注意!