为什么我得到 -2147483648 和 -1 的乘法,负数即 -2147483648,而不是 +2147483648
Why I am getting -2147483648 and -1's multiplication, negative i.e. -2147483648, instead it should be +2147483648
这是我在 Leetcode 中为 this 问题编写的代码片段。
public static int quotient(int dividend,int divisor){
int n=Math.abs(divisor),count=0,ans=Integer.MAX_VALUE-1;
if(Math.abs(dividend)==1 && Math.abs(divisor)==1){
return dividend*divisor;
}
else if(Math.abs(divisor)==1){
if(dividend<0 && divisor<0)
return Math.abs(dividend);
return dividend*divisor;
}
else if(dividend==0){
return 0;
}
else {
while (true) {
if (n > Math.abs(dividend)) {
ans = count;
break;
} else if (n == Math.abs(dividend)) {
ans = count + 1;
break;
} else {
n += Math.abs(divisor);
count++;
}
}
}
if((dividend<0 && divisor>0) || (dividend>0 && divisor<0))
ans*=-1;
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int dividend=sc.nextInt();
int divisor = sc.nextInt();
int ans=quotient(dividend,divisor);
System.out.println(ans);
}
但是此测试用例的代码失败了,我得到的输出为 -2147483648
,预期输出为 2147483648
。我尝试使用 Math.abs(_)
但它也不起作用。
输入:
-2147483648
-1
为什么会这样?请解释。
我认为这是整数溢出。如图here,Long Integer的最大值为2147483647
,没有2147483648
这样的int
值,所以去-2147483648
作为添加 1
时的下一个整数。你可以尝试long
类型来解决这个问题,它的最大值是9223372036854775807
in Java(很多)。
这是我在 Leetcode 中为 this 问题编写的代码片段。
public static int quotient(int dividend,int divisor){
int n=Math.abs(divisor),count=0,ans=Integer.MAX_VALUE-1;
if(Math.abs(dividend)==1 && Math.abs(divisor)==1){
return dividend*divisor;
}
else if(Math.abs(divisor)==1){
if(dividend<0 && divisor<0)
return Math.abs(dividend);
return dividend*divisor;
}
else if(dividend==0){
return 0;
}
else {
while (true) {
if (n > Math.abs(dividend)) {
ans = count;
break;
} else if (n == Math.abs(dividend)) {
ans = count + 1;
break;
} else {
n += Math.abs(divisor);
count++;
}
}
}
if((dividend<0 && divisor>0) || (dividend>0 && divisor<0))
ans*=-1;
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int dividend=sc.nextInt();
int divisor = sc.nextInt();
int ans=quotient(dividend,divisor);
System.out.println(ans);
}
但是此测试用例的代码失败了,我得到的输出为 -2147483648
,预期输出为 2147483648
。我尝试使用 Math.abs(_)
但它也不起作用。
输入:
-2147483648 -1
为什么会这样?请解释。
我认为这是整数溢出。如图here,Long Integer的最大值为2147483647
,没有2147483648
这样的int
值,所以去-2147483648
作为添加 1
时的下一个整数。你可以尝试long
类型来解决这个问题,它的最大值是9223372036854775807
in Java(很多)。