LeetCode-007-整数反转

整数反转

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

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

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

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:字符串遍历

首先获取整数的符号symbol,然后将整数部分转换成字符串,从后往前遍历,得到反转后的字符串result,将symbolresult拼起来就是最终的返回结果。

注意点:考虑转化后的值是否超过整数的范围,如果超过了,返回0。

public class Solution {
    public static int reverse(int x) {
        if (x == 0 || x < Integer.MIN_VALUE || x > Integer.MAX_VALUE) {
            return 0;
        }
        String xStr = String.valueOf(x);
        String symbol = "";
        if (x < 0) {
            symbol = "-";
            xStr = xStr.substring(1);
        }
        String result = "";
        int zeroCount = 0;
        for (int i = xStr.length() - 1; i >= 0; i--) {
            if (xStr.charAt(i) != '0') {
                break;
            } else {
                zeroCount++;
            }
        }
        for (int i = xStr.length() - 1 - zeroCount; i >= 0; i--) {
            result += xStr.charAt(i);
        }
        double doubleResult = Double.valueOf(symbol + result);
        if (doubleResult < Integer.MIN_VALUE || doubleResult > Integer.MAX_VALUE) {
            return 0;
        }
        return Integer.valueOf(symbol + result);
    }

    public static void main(String[] args) {
        System.out.println(reverse(123));
    }
}
posted @   醉舞经阁  阅读(49)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示