Divide Two Integers

自己实现除法 太太太恶心了。。。。
就是用位移代替了乘法,然后不断减去位移得到的乘数*除数
主要是测试数据还有一个Java.MinValue的问题 = = 取了abs之后它居然还是负数。。。我日
public class Solution {
    public int divide(int dividend, int divisor) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int positive = 1;
        if (dividend >0 && divisor < 0 || dividend <0 && divisor > 0 )
            positive = -1;
        if (divisor == Integer.MIN_VALUE) {
            if (dividend == Integer.MIN_VALUE) {
                return 1;
            }
            else {
                return 0;
            }
        }
        if (dividend == Integer.MIN_VALUE) {
            if (positive == -1) {
                return -1 + divide(dividend + divisor, divisor);
            }
            else {
                return 1 - divide(dividend + divisor, divisor);
            }
        }
        dividend = Math.abs(dividend);
        divisor = Math.abs(divisor);
        int result = 0;
        
        while (dividend >= divisor){
            int product = 1;
            int temp = divisor;
            while (dividend - temp >= temp){
                product = product << 1;
                temp = temp << 1;
            } 
            result += product;
            dividend -= temp;
        }
        
        return positive * result;
    }
}

你可能感兴趣的:(Integer)