Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321 Example 2:
Input: -123 Output: -321 Example 3:
Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
这是一道easy的题,需要考虑到的点有余数、除数、以及reverse之后可能会出现的溢出情况。 基本的思路很简单,当 x 不为0的时候,取x/10的余数,然后x/=10,同时开了判断溢出的情况。
看了官方解答,比我想的要简单的一些。

class Solution {
public:
int reverse(int x) {
int res = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (res > INT_MAX/10) return 0;
if (res < INT_MIN/10) return 0;
res = res * 10 + pop;
}
return res;
}
};
需要注意的点:
1、int类型的长度?(这也是本题可以使用INT_MAX、INT_MIN的原因)
2、INT_MAX、INT_MIN(老是忘记=_=)
3、在思考的时候尽量想好最简洁的算法。