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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Personal tips: 很简单但是32位的限定是个头疼的地方。实际上可以用long储存然后再转换成int类型。自己的代码中给出的是全int类型的实现。以下为代码:
class Solution {
public:
int reverse(int x) {
int rev = 0, flag = 0;
if (x < 0) flag = 1;
while (x!=0)
{
if (((INT_MAX - x % 10) / 10 < rev&&flag==0) || ((INT_MIN - x % 10) / 10 > rev&&flag==1)) { return 0; }
rev = x % 10 + 10 * rev;
x /= 10;
}
return rev;
}
};