算法leetcode|7. 整数反转(rust重拳出击)



7. 整数反转:

给你一个 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

分析:

  • 面对这道算法题目,二当家的陷入了沉思。
  • 从最后一位逐渐向前拼接,可以想像成栈数据结构,取出最后一位放到结果的最后一位,这样循环完毕相当于整体反转,唯一要注意的就是处理超过32位有符号数的范围。

题解:

rust:

impl Solution {
    pub fn reverse(mut x: i32) -> i32 {
        let max = i32::MAX / 10;
        let min = i32::MIN / 10;
        let mut ans = 0;
        while x != 0 {
            if ans > max || ans < min {
                return 0;
            }
            ans = ans * 10 + x % 10;
            x /= 10;
        }

        ans
    }
}

go:

func reverse(x int) (ans int) {
    for x != 0 {
        if ans < math.MinInt32/10 || ans > math.MaxInt32/10 {
            return 0
        }
        digit := x % 10
        x /= 10
        ans = ans*10 + digit
    }
    return
}

c++:

class Solution {
public:
    int reverse(int x) {
        int ans = 0;
        while (x != 0) {
            if (ans < INT_MIN / 10 || ans > INT_MAX / 10) {
                return 0;
            }
            int digit = x % 10;
            x /= 10;
            ans = ans * 10 + digit;
        }
        return ans;
    }
};

python:

class Solution:
    def reverse(self, x: int) -> int:
        INT_MIN, INT_MAX = -2**31, 2**31 - 1
        ans = 0
        while x != 0:
            if ans < INT_MIN // 10 + 1 or ans > INT_MAX // 10:
                return 0
            digit = x % 10
            if x < 0 and digit > 0:
                digit -= 10
            x = (x - digit) // 10
            ans = ans * 10 + digit
        return ans


java:

class Solution {
    public int reverse(int x) {
        final int max = Integer.MAX_VALUE / 10;
		final int min = Integer.MIN_VALUE / 10;
		int       ans = 0;
		while (x != 0) {
			if (ans > max || ans < min) {
				return 0;
			}
			ans = ans * 10 + x % 10;
			x /= 10;
		}
		return ans;
    }
}


非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~


评论 43
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二当家的白帽子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值