I. Title Description
Divide-integers without using multiplication, division and mod operator.
If It is overflow, return max_int.
Two. Topic analysis
The meaning of the topic is simple and straightforward, which requires not using multiplication, division, and remainder mods, entering two integers, and outputting the result of the division operation.
Go out multiplication method, the remaining only add subtraction and bit operation, it is not difficult to think of, and directly using subtraction, dividend minus the divisor size of the value, the record is reduced number of times, it is certainly possible to get the same result as division operation, but the method compared to a fool, and will time out, the complexity of O (n).
The complexity of O (LOGN) can be achieved by using bit operations, but it is not so easy to think of a specific operation, first of all, we know that any integer can be represented as a set of linear combinations of bases based on a power of 2, num = flag0 * 2^0 + flag1 * 2^1 + flag2 * 2^2 + ... + flagn * 2^n
where the flag0, flag1, flag2, ..., flagn
value is 0 & 1
.
Based on the above facts, if the order is: dividend / divisor = num
dividend = divisor * num = divisor * (flag0 * 2^0 + flag1 * 2^1 + flag2 * 2^2 + ... + flagn * 2^n)
For divisor, use the shift operation << make it double each time, thus reducing the number of times to seek quotient. Here are the steps:
- When the divisor is greater than the divisor, the divisor is multiplied by 2 (the code uses the variable step to record each divisor by 2) until step is greater than dividend. Record the number of shift operations I.
- If the dividend is greater than the divisor, then dividend minus step. Until the divisor is less than the divisor. Save the results.
- Output result.
Note:
byte:128~127 (1Byte)short :32768~32767 (2Bytes)int:-2147483648~2147483647 (4Bytes)long:-9223372036854774808~9223372036854774807 (8Bytes)
Three. Sample code
classSolution { Public:intDivideintDividend,intDivisor) {if(Dividend = =0|| divisor = =0)return 0;if(Dividend = = Int_min && divisor = =-1)returnInt_max;//Overflow BOOLNegative = (Dividend >0&& Divisor <0) || (Dividend <0&& divisor >0);LongPositivedividend =ABS(Long(dividend));LongPositivedivisor =ABS(Long(divisor));Longresult =0; while(Positivedividend >= Positivedivisor)//dividend greater than divisor{LongStep = positivedivisor; for(inti =0; Positivedividend >= Step; ++i, Step <<=1) {positivedividend = Positivedividend-step; Result + =1<< i; } }returnNegative? -result:result; }};
Four. Summary
Using bit arithmetic to solve this kind of problem is quite easy to think about, but how to do it is another matter.
Leetcode notes: Divide, integers