#leetcode#Divide Two Integers

Difference between >>> and >>:

http://stackoverflow.com/a/2811372/2345313

学习了code ganker大神的代码, 自己实际写的时候还是漏洞百出, 比如typo,还有忘记把dividend 和 divisor赋值成相应的绝对值, 

举个例子: 129 / 7, 除法其实就是看129里有多少个7, 常规思路可以while(dividend > divisor){divident -= divisor; counter++}, 记录一共减去多少个除数, 则count就是结果值, 但是这样的话复杂度是O(n), n是结果大小, 


更快的话就是利用位运算, divisor << 1 就是 除数 * 2, 7 * 2 = 14, times = 1, 14 * 2 = 28, times = 2, 28 * 2 = 56, times = 3, 56 * 2 = 112, times = 4, 112 * 2 = 224 > 129, 所以第一个while循环就结束了, 

第二个while循环中, 依次以112, 56, 28, 7为基, 比如  129 > 112,  则 dividend = 129 - 112 = 17, result = 1 << times, 也就是 1<<4, 等于16, 因为 112 是 7 左移四次得到的, 也就是说有16个7已经被减去了.......

这样被除数是依次减去除数的2的n次幂, 所以时间复杂度是 O(logn), 效率高很多


另外需要注意对Integer.MIN_VALUE的讨论, 这个值比较特殊, Math.abs(Integer.MIN_VALUE)依旧是 Integer.MIN_VALUE, 我在 Reverse Integer 中已经讨论过了

public class Solution {
    public int divide(int dividend, int divisor) {
        if(dividend == 0){
            return 0;
        }
        if(divisor == 1){
            return dividend;
        }
        if(divisor == 0){
            return Integer.MAX_VALUE;
        }
        boolean isNeg = (dividend ^ divisor) >>> 31 == 1;
        int res = 0;
        if(dividend == Integer.MIN_VALUE){
            if(divisor == -1){
                return Integer.MAX_VALUE;
            }
            dividend += Math.abs(divisor);
            res++;
        }
        if(divisor == Integer.MIN_VALUE){  // if dividend is MIN(-2147483648), then res already ++, is 1, if dividend is any other number, abs(dividend) < abs(MIN), so is 0, return res which value is 0;
            return res;
        }
        int times = 0;  //current times that divisor multiply by 2
        divisor = Math.abs(divisor);
        dividend = Math.abs(dividend); // forgot to make them equals to abs(), cannot pass 1 / -1, because -1 will always <= 1 >> 1, which is 0...
        while(divisor <= dividend >> 1){
            divisor = divisor << 1;
            times++;
        }
        
        while(times >= 0){
            if(dividend >= divisor){
                res += 1 << times;
                dividend -= divisor;
            }
            divisor = divisor >> 1;
            times--;
        }
        return isNeg ? -res : res;
    }
}


你可能感兴趣的:(LeetCode)