Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
巧用模除逆转整数,超出32位的有符号整数反转后若溢出返回0。
class Solution {
public:
int reverse(int x) {
int ans = 0;
while (x) {
int temp = ans * 10 + x % 10;
if (temp / 10 != ans)
return 0;
ans = temp;
x /= 10;
}
return ans;
}
};