问题描述
这是我为Leetcode中的此问题编写的代码段.
This is the code snippet I had written for this question in 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(_)
,但它也不起作用.
but this code is failing for this test case and I am getting its output as -2147483648
and the expected output is 2147483648
. I tried using Math.abs(_)
but it is also not working.
输入:
-2147483648-1
为什么会这样?请解释.
Why is this happening? Please explain.
推荐答案
我认为这是一个整数溢出.如此处所示,Long Integer的最大值为 2147483647
,并且没有这样的 int
值作为 2147483648
,因此当添加 1
-2147483648 >.您可以尝试使用 long
类型来解决此问题,在Java中,最大值为 922337203685477575807
.
I think this is an Integer overflow. As shown here, the maximum value of Long Integer is 2147483647
, and there is no such int
value as 2147483648
, so it goes to -2147483648
as the next integer when adding 1
. You can try the long
type for solving this problem, its maximum is 9223372036854775807
in Java (that's a lot).
这篇关于为什么我得到-2147483648和-1的负数,即-2147483648,所以应该是+2147483648的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!