gpt4 book ai didi

java - 反转 int 限制内的整数值

转载 作者:行者123 更新时间:2023-12-05 08:30:55 25 4
gpt4 key购买 nike

我想反转一个整数。我尝试了以下代码,当数字太大以至于它的反向大于 int 限制(例如 1534236469)时会出现问题,因此在这种情况下它会返回一些垃圾整数。

如何使用 Integer.MIN_VALUEInteger.MAX_VALUE 检查反转后的数字是否在限制范围内?

注意:只能使用int变量类型。

int num = 1534236469;

int reverseInt = 0;
int multiplier = 1;

if ( num < 0 ) {
multiplier *= -1;
}

while ( num != 0 ) {

//get the last digit
int digit = num % 10;

//multiply the reverseInt by 10 and then add the last digit
reverseInt = (reverseInt * multiplier) + digit;

multiplier = 10;
num /= 10;
}

//how to fix this.
if (reverseInt < Integer.MIN_VALUE || reverseInt > Integer.MAX_VALUE ) {
System.out.println("Invalid number");
} else {
System.out.println("Reversed integer is " + reverseInt);
}

最佳答案

您只需在添加下一个数字之前进行检查,这样您就可以简单地将检查移至实际计算中。如果您当前的反向正数大于 Integer.MAX_VALUE/10,则您无法添加其他数字。负数也是如此。

我唯一做的就是将你的这部分代码移上去:

if (reverseInt < Integer.MIN_VALUE || reverseInt > Integer.MAX_VALUE ) {
System.out.println("Invalid number");
} else {

然后我添加了 /10 和一个 return 语句,因为程序必须在溢出时结束:

public class StackOverflowTest {
public static void main(String[] args) {
int num = -1534236469;

int reverseInt = 0;
int multiplier = 1;

if ( num < 0 ) {
multiplier *= -1;
}

while ( num != 0 ) {

// if this next step will push is into overflow, then stop:
if (reverseInt < Integer.MIN_VALUE/10 || reverseInt > Integer.MAX_VALUE/10) {
System.out.println("Invalid number");
return;

} else {

//get the last digit
int digit = num % 10;

// multiply the reverseInt by 10 and then add the last digit
reverseInt = (reverseInt * multiplier) + digit;
}

multiplier = 10;
num /= 10;
}

System.out.println("Reversed integer is " + reverseInt);
}
}

或者,您可以将其视为字符串,然后简单地反转字符串(连同符号摆弄):

public class StackOverflowTest {
public static void main(String[] args) {

reverse(1534236469);
System.out.println();
reverse(-153423646);
}

public static void reverse(int num) {
System.out.println("int = " + num);
int number = num < 0 ? -num : num; // remove the sign

String reverse = new StringBuilder(String.valueOf(number)).reverse().toString();
System.out.println("reverse String: " + reverse);

try {
int reversed = Integer.parseInt(reverse);
reversed = num < 0 ? -reversed : reversed; // get back the sign
System.out.println("Reversed integer is " + reversed);
} catch (NumberFormatException ex) {
System.out.println("Invalid number");
}
}
}

打印:

int = 1534236469
reverse String: 9646324351
Invalid number

int = -153423646
reverse String: 646324351
Reversed integer is -646324351

关于java - 反转 int 限制内的整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61529979/

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