LEETCODE-Reverse Integer

本文探讨了如何实现整数反转算法,并详细解释了如何处理反转后的整数可能引起的溢出问题。包括特殊情况处理(如末尾为0的整数),以及输入为32位整数时的溢出行为。文中提供了一个完整的解决方案,通过引入辅助函数判断溢出,并最终返回正确的反转结果或默认值0。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 == 0return 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这一题差不多反转的过程都是:
将原数的最后一位给到新数;
然后原数去除最后一位;
新数将得到的位依次向后排列;
最后原数一位也没有了;
而新数也反转完毕了;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值