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.
Subscribe to see which companies asked this question.
class Solution {
public:
int reverse(int x) {
int y = x %100;
if(x >= 2147483648 || x < -2147483648 || x==0) return 0; //溢出
else if(x/1000000000>0 && (y>=22 || y<=-22)) return 0; //溢出
int sign = 0;
if(x>=0) sign = 1;
else sign = -1;
x=x*sign;
int ans = 0;
while(x > 0){
ans = ans*10 + x%10;
x = x/10;
}
if(ans >= 2147483648 || ans < 0) return 0; //溢出
else return ans*sign;
}
};