程序员算法题每天一练0007. 整数反转(多种语言实现)

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

C++

#include <climits>
#include <iostream>
using namespace std;
class Solution {
public:
    int reverse(int x) {
        int ans = 0;
        for (; x; x /= 10) {
            if (ans < INT_MIN / 10 || ans > INT_MAX / 10) {
                return 0;
            }
            ans = ans * 10 + x % 10;
        }
        return ans;
    }
};

void main()
{
    Solution sol;
    int data = 123;
    int ret = sol.reverse(data);
    cout << ret << endl;

}

c#

public class Solution
{
    public int Reverse(int x)
    {
        int ans = 0;
        for (; x != 0; x /= 10)
        {
            if (ans < int.MinValue / 10 || ans > int.MaxValue / 10)
            {
                return 0;
            }
            ans = ans * 10 + x % 10;
        }
        return ans;
    }
    public static void Main(string[] args)
    {
        Solution sol = new Solution();
        int x = 123;
        int ret = sol.Reverse(x);
        Console.WriteLine(ret);
    }
}

Python

from typing import ChainMap


class Solution:
    def reverse(self, x: int) -> int:
        ans = 0
        mi, mx = -(2**31), 2**31 - 1
        while x:
            if ans < mi // 10 + 1 or ans > mx // 10:
                return 0
            y = x % 10
            if x < 0 and y > 0:
                y -= 10
            ans = ans * 10 + y
            x = (x - y) // 10
        return ans
 
solution = Solution()
result = solution.reverse(123)
print(result)

Java

class Solution {
    public int reverse(int x) {
        int ans = 0;
        for (; x != 0; x /= 10) {
            if (ans < Integer.MIN_VALUE / 10 || ans > Integer.MAX_VALUE / 10) {
                return 0;
            }
            ans = ans * 10 + x % 10;
        }
        return ans;
    }
	
    public static void main(String[] args) {
        Solution sol = new Solution();  // 创建Solution类的实例
        int x = 123;
        int result = sol.reverse(x);   
        System.out.println(result);  // 打印结果
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值