Discription:
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.
Solution:
int reverse(int x) {
long long rev = 0; //更换数据类型
while (x!=0){
rev = rev * 10 + x % 10;
x = x / 10;
}
if (rev > INT_MAX || rev < INT_MIN)
return 0;
return (int)rev;
}
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;
}
GitHub-Leetcode:https://github.com/wenwu313/LeetCode