7. 整数反转

题目描述

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例

示例 1:
输入: 123
输出: 321
 示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21

解题思路1

利用64位数字计算,判断是否超出32未的表示范围,如果超出返回0.

C++

class Solution {
public:
    int reverse(int x) {
        long int ans = 0;
        long int xx = (long int)x;
        long int max = (long int)INT_MAX + 1;
        bool negtive = false;
        if (xx < 0) negtive = true, xx = -xx;
        while(xx)
        {
            int b = xx % 10;
            xx = xx / 10;
            ans = ans * 10 + b;
        }
        
        if ((!negtive && ans > INT_MAX) ||
            (negtive && ans > max) )
        {
                ans = 0;
        }
        
        if (negtive) ans = -ans;
        
        return ans;
    }
};

python

python3中的int是无限的。

class Solution:
    def reverse(self, x: int) -> int:
        max_value = 2147483647
        min_value = -2147483648
        ans = 0
        negtive = False
        if x < 0:
            negtive = True
            x = -x
        while(x):
            b = x % 10
            ans = ans * 10 + b
            x = x // 10
        if ans > max_value or ans < min_value:
            ans = 0
        if negtive:
            ans = -ans
        return ans
        

解题思路2

不借助64位数字,直接在32位数字的范围内完成。

C++


python


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容