力扣(LeetCode)7. 整数反转(2022.01.07)

力扣(LeetCode)7. 整数反转(2022.01.07),第1张

力扣(LeetCode)7. 整数反转(2022.01.07)

 给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

示例 1:

输入:x = 123
输出:321

示例 2:

输入:x = -123
输出:-321

示例 3:

输入:x = 120
输出:21

示例 4:

输入:x = 0
输出:0

提示:

-231 <= x <= 231 - 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer

方法一:对10取模,得到尾数,乘10相加,得到结果,最后进行范围判断即可。

C++提交内容:

class Solution {
public:
    int reverse(int x) {
        long res = 0;
        while(x != 0){
            int num = x % 10;
            x /= 10;
            res = res*10 + num;
        }
        if(res >= pow(-2, 31) && res <= pow(2, 31) - 1){
            return res;
        }else{
            return 0;
        }
    }
};

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5698918.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存