Divide two integers
Divide two integers without using multiplication, division and mod operator.
Solution 1
1. The basic idea is to constantly reduce the divisor until it is 0. But it will be too slow.
2. We can use a two-way method to accelerate this process. Continue to divisor * 2 until it is bigger than the divisor. At the same time, the CNT is also recorded, and the value after the divisor is reduced and the result is + CNT.
Because it is doubled, the speed will be very fast and exponential.
3. In addition, it should be noted that the minimum value is out of the border. Take ABS for the smallest positive number and get it... Because the absolute value of the smallest positive number is greater than the largest positive number (INT)
So we can use long to catch this set.
1 public class solution {2 Public int divide (INT dividend, int divisor) {3 long a = math. ABS (long) dividend); 4 5 // Ref: http://blog.csdn.net/kenden23/article/details/16986763 6 // Note: here you must take long and then abs, otherwise, the minimum value of Int Is abs and the original value is 7 long B = math. ABS (long) divisor); 8 9 int ret = 0; 10 // Here it must be = because when it is equal, it can also be reduced by 11 while (A> = B) {12 // The Judgment condition is> = 13 for (long deduce = B, CNT = 1; A >= deduce; deduce <= 1, CNT <= 1) {14 A-= deduce; 15 RET + = CNT; 16} 17} 18 19 // get the symbol bit. 20 return (dividend> 0) ^ (divisor> 0 )? -RET: ret; 21} 22}
View code
GitHub code:
Divide. Java
Ref: http://blog.csdn.net/fightforyourdream/article/details/16899675
Leetcode: divide two integers solution report