Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
没想出什么好的方法来解决反转后的数据溢出;
通过写了一个Yesorno()判断函数;
就采用将x反转后得到i的y再反转得到z;
判断x与z是否相等;若不相等则判定为发生溢出,return 0;相等则返回y的值;
class Solution {
public:
bool Yesorno(int y, int x){
int z = 0;
while(y){
z = z * 10 + y % 10;
y /= 10;
}
if(z == x)
return 1;
else
return 0;
}
int reverse(int x) {
int y = 0;
// 如果此处不判断是否为零,如x为0则在下面的while陷入死循环;->(如下:)
if( x == 0 )
return 0;
//去掉x末尾的0,避免在Yesorno进行比较时发生错误;例如:x=10 -> y=1 ->z=1(y再进行反转得到的不是10,而是1);->(如下 :)
while( x%10 == 0)
x /= 10;
int X = x;
while(x){
y = y * 10 + x % 10;
x /=10;
}
int Y = y;
if(Yesorno( Y, X))
return y;
else
return 0;
}
};
中心反转算法:
int y = 0;
while(x){
y = y * 10 + x % 10;
x /=10;
}
思想与Reverse Bits这一题差不多反转的过程都是:
将原数的最后一位给到新数;
然后原数去除最后一位;
新数将得到的位依次向后排列;
最后原数一位也没有了;
而新数也反转完毕了;