leetcode reverse-integer题解

本文介绍了一种解决LeetCode上32位有符号整数反转问题的方法,通过将数字转换为正数并逐位反转,最后判断是否超出32位整数范围,避免了整数溢出的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:Given a 32-bit signed integer, reverse digits of an integer.

note:Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

汉语理解:给出一个32位有符号整数的反转表示。

解题思路:将数字首先转换成正数,然后依次从低位获取原始数字正数的每一个数字,获取最低位时这个数字保存在一个变量中res,获取次低位时,将count*10+次低位赋值给count,再获取倒数第三位数字时,将count*10+倒数第三位数字赋值给count,一次类推,即可得到原始数绝对值的反转数字,再根据范围进行约束,防止数值溢出。

代码(java):

class Solution {
    public int reverse(int x) {
        int tag=0;
        if(x<0){
            tag=1;
            x=0-x;
        }
        long res=0;
        while(x>0){
            int tail=x%10;
            res=res*10+tail;
            x=x/10;
        }
        if(tag==1)res=0-res;
        if(res> Integer.MAX_VALUE || res<Integer.MIN_VALUE)res=0;
        return (int) res;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值