LeetCode | 7)Reverse Integer

题目

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

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.


思路

  1. 如果用long保存结果,将结果与INT_MAX比较,返回的时候将long转换为int,则这道题解法将十分简单,代码也少。
  2. 可是如果限定了只能用int存储数值,中间没有任何long到int的转换或者负数到正数的转换,那么还是比较有挑战性的。

代码

class Solution {
public:
    int reverse(int x) {
        int res{0};
        if (x >= 0)
        {
            do {
                if (res > (INT_MAX - x%10)/10)  return 0;
                res = (res<<3) + (res<<1) + x%10;
                //res = res * 10 + x % 10;
            }while (x /= 10);
        }
        else
        {
            do {
                if (res < (INT_MIN - x%10)/10)  return 0;
                res = (res<<3) + (res<<1) + x%10;
                //res = res * 10 + x % 10;
            }while (x /= 10);
        }
        return res;
    }
};

这段代码运用了一个很巧妙的方法来判断乘法溢出问题:
res > (INT_MAX - x%10)/10……………………………….(1)
一般的想法是直接判断 if (res > INT_MAX),但这是有问题的,因为即使运算过程中发生了溢出,结果也永远都小于INT_MAX,所以这个判断是无效的。怎么办呢?将res与缩小了10倍的INT_MAX作比较!将上面的(1)式作变换 res * 10 + x%10 > INT_MAX,可以看到它成功的判断了res = res * 10 + x%10是否大于INT_MAX.

当x<0时,和上面类似,判断if (res < (INT_MIN - x%10)/10)就知道是否出现下溢。这里有一点要注意的是负数取余的结果是负数,所以才能res = res * 10 + x % 10,否则res将是正数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值