gpt4 book ai didi

java - 使用java中的字符串生成器反转数字

转载 作者:行者123 更新时间:2023-12-02 01:43:22 25 4
gpt4 key购买 nike

问题陈述:给定一个 32 位有符号整数,反转整数的数字。

示例1:

输入:123输出:321示例2:

输入:-123输出:-321

我的解决方案:

class Solution7{
public int reverse(int x) {
if(x>Integer.MAX_VALUE || x<Integer.MIN_VALUE) {
return 0;
}


StringBuilder S_rev = new StringBuilder();
String S_r_v=S_rev.append(Math.abs(x)).reverse().toString();//.toString() String builder to String

double reverse_no=Double.parseDouble(S_r_v);

if (x < 0) {
return -(int)reverse_no;
}
return (int)reverse_no;

}

}

我的解决方案对于大多数测试用例来说都可以。但它无法通过一个测试用例,并且出现错误

错误:第10行:java.lang.NumberFormatException:对于输入字符串:“8463847412-”

如果有人知道这是什么类型的错误,请讨论。

提前谢谢您。

最佳答案

您似乎正在尝试传递 Integer.MIN_VALUE

当您传入最小整数值时,Math.abs 似乎返回负数,如此处所述

https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#abs-int-

 Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.

您可以检查 x<=Integer.MIN_VALUE如果 x 是 Integer.MIN_VALUE,则返回 0 或处理 Integer.MIN_VALUE 的特殊情况

 if(x== Integer.MIN_VALUE)
return -8463847412;

关于java - 使用java中的字符串生成器反转数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com