为什么我得到 -2147483648 和 -1 的乘法,负数即 -2147483648,而是应该是 +2147483648

  • 本文关键字:-2147483648 +2147483648 java integer
  • 更新时间 :
  • 英文 :


这是我在Leetcode中为这个问题编写的代码片段。

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

为什么会这样?请解释一下。

我认为这是一个整数溢出。如图所示,Long Integer 的最大值为2147483647,并且没有2147483648这样的int值,所以在添加1时将其作为下一个整数-2147483648。您可以尝试解决此问题的long类型,其最大值在 Java 中9223372036854775807(很多)。

最新更新