[LeetCode-interview algorithm classic-Java implementation] [029-Divide Two Integers (Division of Two Integers)], leetcode -- java
[029-Divide Two Integers (Division of Two Integers )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Theme
If division, multiplication, and remainder are not used, the result of division of two integers is obtained. If overflow exists, the maximum integer is returned.
Solutions
Any integer can be expressed as a linear combination of groups based on the power of 2, that is, num = a_0 * 2 ^ 0 + a_1 * 2 ^ 1 + a_2 * 2 ^ 2 +... + A_n * 2 ^ n. Based on the above formula and the shift left is equivalent to multiply by 2, we first let the divisor move left until it is greater than the devisor to get a maximum base. Next, we try to subtract this base every time. If possible, we add 2 ^ k to the result, and then the base continues the right shift iteration until the base is 0. Because the number of iterations of this method exceeds the result by knowing the power of 2, the time complexity is O (log (n )).
Code Implementation
Algorithm Implementation class
Public class Solution {public int divide (int dividend, int divisor) {// overflow processing when division is performed if (divisor = 0 | dividend = Integer. MIN_VALUE & divisor =-1) {return Integer. MAX_VALUE;} // calculates the int sign = (dividend <0) ^ (divisor <0 ))? -1: 1; // calculates the absolute value. To prevent overflow, use long dvd = Math. abs (long) dividend); long dvs = Math. abs (long) divisor); // record result int result = 0; // The devisor is greater than the devisor while (dvd> = dvs) {// record divisor long tmp = dvs; // record store size long mul = 1; while (dvd >=( tmp <1) {tmp <= 1; mul <= 1 ;} // subtract the exponential value (value: tmp) of the dvs closest to the dvd. dvd-= tmp; // The corrected result is result + = mul;} return result * sign ;}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/47052683]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.