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.