LeetCode 题解(177): Divide Two Integers

题目:

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

题解:

只能用移位运算,以2为基模拟除法。

边界情况: divisor == 0 ==> result = INT_MAX, dividend == INT_MIN, divisor == -1 溢出 ==> result = INT_MAX

dividend == INT_MIN,divisor != -1:

dividend -= abs(divisor), result++。

用base表示基,求divisor不大于dividend的最大值,然后dividend减去divisor,更新result, base和divisor。

C++版:

class Solution {
public:
    int divide(int dividend, int divisor) {
       if(divisor == 0)
           return INT_MAX;
        bool isNeg = abs((dividend ^ divisor) >> 31);
        int result = 0;
        if(dividend == INT_MIN) {
            if(divisor == -1)
                return INT_MAX;
            dividend += abs(divisor);
            result++;
        }
        if(divisor == INT_MIN)
            return result;
        dividend = abs(dividend);
        divisor = abs(divisor);
        int base = 0;
        while(divisor <= (dividend >> 1)) {
            divisor <<= 1;
            base++;
        }
        while(base >= 0) {
            if(dividend >= divisor) {
                result += (1 << base);
                dividend -= divisor;
            }
            divisor >>= 1;
            base--;
        }
        return isNeg ? -result : result;
    }
};

Java版:

public class Solution {
    public int divide(int dividend, int divisor) {
    if(divisor == 0)  
    {  
        return Integer.MAX_VALUE;  
    }  
    boolean isNeg = (dividend^divisor)>>>31 == 1;  
    int res = 0;  
    if(dividend == Integer.MIN_VALUE)  
    {  
        dividend += Math.abs(divisor);  
        if(divisor == -1)  
        {  
            return Integer.MAX_VALUE;  
        }  
        res++;  
    }  
    if(divisor == Integer.MIN_VALUE)  
    {  
        return res;  
    }  
    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<>= 1;  
        digit--;  
    }  
    return isNeg?-res:res;
    }
}

Python版:

class Solution:
    # @param {integer} dividend
    # @param {integer} divisor
    # @return {integer}
    def divide(self, dividend, divisor):
        if divisor == 0:
            return sys.maxint
        if dividend == -2147483648 and divisor == -1:
            return 2147483647
        isNeg = abs((dividend ^ divisor) >> 31)
        dividend = abs(dividend)
        divisor = abs(divisor)
        result, base = 0, 0
        while divisor <= (dividend >> 1):
            divisor <<= 1
            base += 1
        while base >= 0:
            if dividend >= divisor:
                result += (1 << base)
                dividend -= divisor
            divisor >>= 1
            base -= 1
        
        return -result if isNeg else result

你可能感兴趣的:(算法)