[牛客网-Leetcode] #数组 #复杂度 简单 reverse-integer

翻转整数 reverse-integer

题目描述

将给出的整数x翻转。
例1:x=123,返回321
例2:x=-123,返回-321

你有思考过下面的这些问题么?
如果整数的最后一位是0,那么输出应该是什么?比如10,100
你注意到翻转后的整数可能溢出吗?假设输入是32位整数,则将翻转10000000003就会溢出,你该怎么处理这样的样例?抛出异常?这样做很好,但是如果不允许抛出异常呢?这样的话你必须重新设计函数(比如添加一个额外的参数)。

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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

示例

输入

-123

输出

-321

解题思路

  • 此题的关键点在于如何判断溢出,有如下两种思路:
  • 思路1:用long long类型存储结果,如果结果大于0x7fffffff(int能表示的最大整数)或小于0x80000000(int能表示的最小整数)则溢出。
class Solution {
public:
    int reverse(int x) {
        //取绝对值方便处理,最后返回时直接判断x的符号
        int temp = abs(x);  
        //用于大数存储
        vector<int> num;
        //用于存储翻转后的整数
        long long res(0);
        //int能表示的最小和最大整数
        const int minInt = 0x80000000;
        const int maxInt = 0x7fffffff;
        //大数存储
        do {
            num.push_back(temp % 10);
            temp /= 10;
        } while(temp > 0);
        //存储翻转后的整数
        for(int i = 0; i < num.size(); i ++) {
            res = res * 10 + num[i];
        }
        //溢出则直接返回0
        if(res < minInt || res > maxInt) {
            return 0;
        }
        return x > 0 ? (int)res : (int)(-res);
    }
};
  • 思路2:每次计算结果时,用逆运算计算后的结果和原结果比较,如果不相同,则为溢出。
class Solution {
public:
    int reverse(int x) {
        int res(0);
        do {
            //存储尾数
            int tail = x % 10;
            int newRes = res * 10 + tail;
            //如果newRes-tail)/10!=res说明产生了溢出
            if((newRes - tail) / 10 != res) {
                return 0;
            }
            res = newRes;
            x /= 10;
        } while(x != 0);
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值