Divide two integers without using multiplication, division and mod operator.
1 public class Solution { 2 public int divide(int dividend, int divisor) { 3 if(dividend ==0 || divisor==1) 4 return dividend; 5 int sign =1; 6 if(dividend<0) 7 sign *=-1; 8 if(divisor<0) 9 sign*=-1; 10 long res = 0; 11 long div = Math.abs((long) dividend);// don‘t forget the abs! 12 long dis = Math.abs((long) divisor); 13 long [] b = new long[32]; 14 int start = 0; 15 while(dis<=div && start<32){ // here don‘t forget <32 16 b[start] = dis; 17 dis = dis<<1; 18 start++; 19 } 20 start--; 21 while(div>0 && start>=0){ 22 if(div-b[start]>=0){ // just like this 23 res += 1<<start; 24 div-=b[start]; 25 } 26 start--; 27 } 28 return (int) sign*(int)res; 29 } 30 }