Title Link: https://leetcode.com/problems/divide-two-integers/
Divide-integers without using multiplication, division and mod operator.
If It is overflow, return max_int.
int divide (int dividend, int divisor) { if (dividend = = Int_min && Divisor = =-1) //divisor is-2147483648 divisor is-1, Quotient overflow return int_max;int quotient = 0;int flag = (Dividend>0&&divisor>0 | | dividend<0&&divisor <0)? 1: -1;unsigned int a = dividend > 0? Dividend:-dividend; Unsigned integer prevents 2147483648 to overflow after absolute value unsigned int b = divisor > 0? Divisor:-divisor; unsigned int tmp = A; int digit = 0; The number of Bits while (tmp >= b) { //the number of bits of the quotient ++digit; TMP >>= 1; } while (digit--) { //written calculation process similar to division, starting from the highest bit in addition to calculating the number of the quotient of the number of digits unsigned int divi = b << digit; After the divisor is 0 so that except dividend get single digit quotient = (quotient << 1) + (a >= divi? 1:0); After the quotient shift of the high position to be weighted (left Shift weighted 2) a = a >= divi? a-divi:a; } if (flag < 0) quotient =-quotient; return quotient;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
#29 Divide integers