ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

leetcode-7. Reverse Integer

2021-02-14 17:30:11  阅读:187  来源: 互联网

标签:10 return Reverse INT res rev int Integer leetcode


7. Reverse Integer

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

 

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Example 4:

Input: x = 0
Output: 0

Constraints:

  • -231 <= x <= 231 - 1

 

解法: 此题的意思就是将给定的一个数进行反转,如果存在溢出情况就返回0。

将数字进行反转并不难,可以除10取余数进行操作,此问题的关键就是要判断溢出时的情况

因为输入的数字是int型,所以它的范围就是[INT_MIN,INT_MAX],即-2147483648~2147483647 之间。

那么res最大的情况就是214748364,因为x是一个整数,在可能溢出的情况下其开始的第一位是1或者2,

所以 res 只能是 2147483641 或 2147483642 都在 int 的范围内,但是它们对应的x为 1463847412 和 2463847412,

后者超出了数值范围。所以当过程中 res 等于 214748364 时, 输入的x只能为 1463847412, 翻转后的结果为 2147483641,都在正确的范围内。

class Solution {
public:
    int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (abs(res) > INT_MAX / 10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
};

还有另一种方法就是直接判断溢出是与INT_MAX或者INT_MIN进行比较,详细的解释可以查看leetcode

class Solution {
public:
    int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
            if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
};

 

标签:10,return,Reverse,INT,res,rev,int,Integer,leetcode
来源: https://blog.csdn.net/Alatebloomer/article/details/113809045

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有