LeetCode-7. 整数反转

165 阅读1分钟

1.题目描述

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

Tips: 力扣地址:leetcode-cn.com/problems/re…

2. 思路分析

  • 首先处理特殊的情况0,如果是0直接返回。
  • 然后将负数换成整数,同时将int类型强制转换成long型
  • 将数据%10获取最高位的数字,将数字存入StringBuilder中,然后将数据除以10
  • 字符串中的数据已经就反转过来了,然后将字符串解析成long就可以了
  • 解析出来的值和Integer.MIN_VALUE作对比,大于就返回0

3. AC代码

class Solution {
public int reverse(int x) {
        long current = (long)x;
        if(x == 0){
            return 0;
        }
        boolean negative = false;
        //首先判断正负
        if(x < 0){
            current = (-current);
            negative = true;
        }
        //%10读取最小值
        StringBuffer stringBuffer = new StringBuffer();
        do{
            stringBuffer.append(current%10);
            current = current / 10;
        }while (current > 0);
        //根据Long判断数值
        long value = Long.parseLong(stringBuffer.toString());
        if(negative){
            if(-value < Integer.MIN_VALUE){
                return 0;
            }else{
                return (int)-value;
            }
        }

        if(value > Integer.MAX_VALUE){
            return 0;
        }else{
            return (int)value;
        }
    }
}

运行结果:

image.png

4. 总结

上述方法主要是通过取模和除法的运算将数字倒转,然后将字符串重新解析成数字,这个过程需要考虑一些临界值。这个方式也是比较容易想到的解题方法。

我是蚂蚁背大象,文章对你有帮助点赞关注我,文章有不正确的地方请您斧正留言评论~谢谢