Title:
Divide-integers without using multiplication, division and mod operator.
If It is overflow, return max_int.
Test Instructions:
Divides two integers without multiplication, division, and take-rest operations.
If it overflows, it returns Max_int.
Algorithm Analysis:
Reference Blog http://blog.csdn.net/linhuanmars/article/details/20024907
* We know that any integer can be represented as a linear combination of a set of bases at the base of a power of 2, namely num=a_0*2^0+a_1*2^1+a_2*2^2+...+a_n*2^n. Based on the above formula and moving left one phase
when in multiplied by 2,
* Let's move the divisor to the left until it is greater than dividend before getting a maximum base. And then each time we try to subtract the base, if we can add 2^k to the result, then the base continues to move the iteration right until
Base is 0 So far.
* Because the iteration number of this method is 2 to the power until the result is exceeded, the time complexity is O (logn).
AC Code:
<span style= "FONT-SIZE:12PX;" >public class solution{public int divide (int dividend, int divisor) {if (divisor = = 0) { return integer.max_value; } Boolean Isneg = (dividend^divisor) >>>31 = = 1;//above sentence unsigned right move one! is in binary code! ^ for XOR or arithmetic int res = 0; if (dividend = = integer.min_value) {dividend + = math.abs (divisor);//Because the test data appears-2147483648, it cannot be turned into positive ( 2147483648 overflow), so precede with a divisor if (divisor = =-1) {return integer.max_value; } res++; if (divisor = = Integer.min_value) {return res;//here the absolute value of the divisor is maximum, any number divided by this number, the absolute value of the result will eventually be less than 1, rounding is 0. } dividend = Math.Abs (dividend); divisor = Math.Abs (divisor); int digit = 0; while (divisor <= (dividend>>1)) {divisor <<= 1; digit++; } while (digit>=0) {if (dividend>=divisor) {res + = 1<<digit;//(res=res+ (1*2^digit))---> results added 2^k dividend -= divisor; } divisor >>= 1; digit--; } return isneg?-res:res; }}</span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetoode] [Java] Divide integers