题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
解答:
class Solution {
public:
int reverse(int x) {
int k = x < 0 ? -1 : 1;
int abs = x * k;
int rtn = 0;
while(abs > 0) {
int tmp = abs % 10;
//判断一个正数是否溢出
if (rtn > (INT_MAX - tmp) / 10) {
return 0;
}
rtn = tmp + rtn * 10;
abs = abs / 10;
}
return rtn * k;
}
};