关于java:LeetCode007整数反转

2次阅读

共计 956 个字符,预计需要花费 3 分钟才能阅读完成。

整数反转

题目形容:给你一个 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));
    }
}

$$
公式
$$

正文完
 0