关于java:LeetCode007整数反转

整数反转

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

如果反转后整数超过 32 位的有符号整数的范畴

$$
[−2^{31}, 2^{31} – 1]
$$

,就返回 0。

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

示例阐明请见LeetCode官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:字符串遍历

首先获取整数的符号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));
    }
}

$$
公式
$$

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据