您的位置:首页 > 其它

LEETCODE-Reverse Integer

2015-10-18 13:26 323 查看
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 +
4000
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这一题差不多反转的过程都是:

将原数的最后一位给到新数;

然后原数去除最后一位;

新数将得到的位依次向后排列;

最后原数一位也没有了;

而新数也反转完毕了;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  反转数