整数反转

整数反转

https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnx13t/

https://leetcode-cn.com/problems/reverse-integer/

逐位运算

使用x % 10取得个位数的值,将它加到临时值ret中,并且让ret倍增10。

使用x /= 10来去掉个位(C++)。

INT_MIN / 10INT_MAX / 10来提前判断是否会越界

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int reverse(int x) {
int ret = 0;

while (x != 0) {
if (ret < INT_MIN / 10 || ret > INT_MAX / 10) {
return 0;
}
int last = x % 10;
x /= 10;
ret = 10 * ret + last;
}


return ret;
}