Question:
Divide two integers without using multiplication, division and mod operator.
Train of Thought Analysis
In the binary method, the divisor is multiplied, and the result is also doubled until the divisor value is greater than the divisor value. Then, the divisor is used to subtract the divisor and finally increase to a value smaller than the divisor value to obtain the result recursively.
Example: 123/4
4 <123 4*2 = 8 <123 8*2 = 16> 123 16*2 = 32 <123
32*2 = 64 <123 64*2 = 128> 123 The result is increased by 64/4 = 16.
Use 123-64 = 59 and recursively obtain the result again. The final result is 59/4 = 14, and the remainder is 3 <4 discard.
Therefore, the final value is 16 + 14 = 30.
Code:
1 public Solution{ 2 public: 3 long long interDivide(unsigned long long dividend, 4 unsigned long long divisor){ 5 if(dividend<divisor) return 0; 6 7 long long result=1; 8 unsigned long long tmp=divisor,left; 9 10 while(tmp<=dividend){11 left=dividend-tmp;12 tmp<<=1;13 14 if(tmp>dividend){15 break;16 }17 18 else{19 result<<=1;20 }21 }22 23 return result+interDivide(left,divisor);24 }25 26 int Divide(int dividend,int divisor){27 unsigned long long _dividend=abs((long long)dividend);28 unsigned long long _divisor=abs((long long)divisor);29 30 bool positive=((dividend>=0) && (divisor>0)) || ((dividend<=0) && (divisor<0));31 32 return positive?interDivide(_dividend,_divisor):(-1)*interDivide(_dividend,_divisor);33 34 }35 };
Unsigned long is used to prevent overflow.
Leetcode-divdend two integers