Skip to content

Commit

Permalink
Create 29. Divide Two Integers.java
Browse files Browse the repository at this point in the history
  • Loading branch information
Mahesh-addagatla authored May 15, 2024
1 parent a964a52 commit c32e260
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions 29. Divide Two Integers.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution {
public int divide(int dividend, int divisor) {
if(dividend==divisor)return 1;
boolean sign=true;
if((dividend<0 && divisor>0)||(dividend>0 && divisor<0))sign=false;
long n=Math.abs((long)dividend);
long d=Math.abs((long)divisor);
//divisor=Math.abs(divisor);
long quotient=0;
for(int i=30;i>=0;i--){
if( n>=(d<<i)){
quotient+=(1<<i);
n-=(d<<i);
}
}
if(dividend==(Integer.MIN_VALUE) && divisor==1)return Integer.MIN_VALUE;

return (int)(sign?quotient:-quotient);

}
}

0 comments on commit c32e260

Please sign in to comment.