Topic
Divide-integers without using multiplication, division and mod operator.
If It is overflow, return max_int
Link
https://leetcode.com/problems/divide-two-integers/
Answer
1, the maximum value of int max_int is Power (2,31)-1 = 2147483647
2, the minimum value of int min_int is-power (2,31) = 2147483648
3. Overflow occurs when Min_int is divided by-1, because the resulting value is greater than max_int
4, the highest bit of the signed number is 1 o'clock, indicating negative numbers, so you can use the XOR operation to obtain the symbol of the quotient
5, the various versions of ABS look here, double abs (double),long abs (long) unexpectedly in C + +, in fact, I would like to write a method of absolute value, but, hand shake or search the prototype abs.
5, this is the most serious, just start to see the topic, I do not know how to use bit arithmetic to achieve division, first search answers
Then think about the principles, why you can do so, my reasoning is as follows, if there is a problem, please point out, thank you. Below I have ^ expression index, do not mix with C + + ^.
A = b * x (x is the required quotient, the equals sign should be approximately equal)
Any integer can be represented in binary, so x=2^m + 2^n + ... + 2^t, where m > N > T,m,n,t are integers.
X can also represent x = 1*2^m + 0 * 2^ (m-1) + 1 * 2^ (m-2) + ... + (1 or 0) *2^0.
In fact, X can also say:
x = (2^k + 2^ (k-1) + ... + 2^0) + (2^t + 2^ (t-1) +/... + 2^0) + ... + (2^r + 2^ (r-1) + ... + 2^0), where K > t & is not a Gt ... > R.
So a = b * (2^k + 2^ (k-1) + ... + 2^0) +b * (2^t + 2^ (t-1) + ... + 2^0) + ... + b * (2^r + 2^ (r-1) + ... + 2^) + +/- 0).
The first time is a-B * (2^k + 2^ (k-1) + ... + 2^0) = b * (2^t + 2^ (t-1) + ... + 2^0) + ... + * (2^r + 2^ (r-1) + ...). + 2^0)
The second time is a A-B * (2^k + 2^ (k-1) + ... + 2^0)-B. * (2^t + 2^ (t-1) + ... + 2^0) = ... + b * (2^r + 2^ (r-1) + ...) + 2^0)
Push here, everyone should understand.
Code
1 classSolution {2 Public:3 Static Const intMax_int =2147483647;4 Static Const intMin_int =-2147483648;5 6 intDivideintDividend,intdivisor) {7 if(Dividend = = Min_int && divisor = =-1)8 {9 returnMax_int;Ten } One A LongPre = ABS ((Long) dividend); - LongPost = ABS ((Long) divisor); - intindex; the intREM =0; - - while(Pre >=Post) - { + LongTMP =Post; - for(index =0; Pre >= TMP; Index + +, TMP <<=1) + { APre-=tmp; atREM + = (1<<index); - } - } - - return(Dividend >> to) ^ (Divisor >> to) ? -Rem:rem; - } in};
View Code
leetcode-"Medium Problem" Divide, integers