问题
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);
}
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.
Inputs:
-2147483648 -1
Why is this happening? Please explain.
回答1:
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).
来源:https://stackoverflow.com/questions/64832530/why-i-am-getting-2147483648-and-1s-multiplication-negative-i-e-2147483648