Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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.
Solution
转换过程很简单,主要是溢出的判断(依据时,如果计算过程溢出,则是运算是不可逆的)。
class Solution {
public:
int reverse(int x) {
int res=0;
int ress=0;
while(x){
ress=res*10+x%10;
if(res!=(ress/10)) return 0;//溢出的判断
res=ress;
x=x/10;
}
return res;
}
};