【LeeCode】7. 整数反转

时间:2023-01-08 14:01:36

【题目描述】

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

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

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

​​https://leetcode.cn/problems/reverse-integer/

【示例】

【LeeCode】7. 整数反转

【代码】​​官方​

// 2023-1-8
import java.util.*;

class Solution {
public int reverse(int x) {
// 如果越界,默认返回的是0 所以可以初始为0
long res = 0;

while (x != 0){
// 弹出 x 的末尾数字 digit
// 将数字 digit 推入 rev 末尾
res = res * 10 + x % 10;
x /= 10;
}
// 题目里有说明,max要减少1 min不用
if (res > Integer.MAX_VALUE - 1 || res < Integer.MIN_VALUE)
return 0;
// 注意还原回来
int Result = (int) res;
if (x >= 0){
return Result;
}else {
return -Result;
}

}
}

public class Test {
public static void main(String[] args) {
new Solution().reverse(1534236469); // 输出: 0, 这里越界了返回0即可
new Solution().reverse(123); // 输出: 321
new Solution().reverse(-123); // 输出: -321
new Solution().reverse(120); // 输出: 21
new Solution().reverse(0); // 输出: 0
}
}

【代码】admin

注意如果翻转后输入的数字太大了, 容易越界,要对异常进行捕获处理

思路: 整形转字符串,然后利用StringBuilder().reverse()进行翻转

       翻转后的字符利用Integer.parseInt()转换int即可

       另:对输入的数字要进行判断, 负数反转后还是负数

// 2023-1-8
import java.util.*;

class Solution {
public int reverse(int x) {
int res;
if ( x < 0 ){
String str = new StringBuilder(String.valueOf(Math.abs(x))).reverse().toString();
// 注意增加对异常的处理
try {
res = Integer.parseInt(("-" + str));
}catch (Exception e){
return 0;
}
System.out.println(res);
return res;
}
try {
// 注意增加对异常的处理这里会自动处理 021 --> 21
res = Integer.parseInt(new StringBuilder(String.valueOf(x)).reverse().toString());
}catch (Exception e){
return 0;
}
// System.out.println(res);
return res;
}
}

public class Test {
public static void main(String[] args) {
new Solution().reverse(1534236469); // 输出: 0, 这里越界了返回0即可
new Solution().reverse(123); // 输出: 321
new Solution().reverse(-123); // 输出: -321
new Solution().reverse(120); // 输出: 21
new Solution().reverse(0); // 输出: 0
}
}