Leecode Week14: Divide Two Integers

Week14: Divide Two Integers

Difficulty:Medium

1.Problem

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

If it is overflow, return MAX_INT.

2.Algorithm

1.首先判断divisor是否为0,以及dividend == INT_MIN && divisor == -1,若存在以上两种情况,则返回INT_MAX

2.若不存在以上两种情况,判断商的符号位

3.取divisor和dividend的绝对值,设ans为商且初始值为0

4.若dividend大于或等于divisor,左移divisor直到大于dividend,记录左移的位数s
那么temp=divisor<<(s-1)dividend-=tempans+=ans+(1<<(s-1))

5.重复4步骤直到dividend小于divisor

6.返回带符号位的ans

3.Solution

class Solution {
public:
    int divide(int dividend, int divisor) {
        if(!divisor || (dividend == INT_MIN && divisor == -1)) {
            return INT_MAX;
        }
        int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
        long long dvd = labs(dividend);
        long long dvs = labs(divisor);
        int ans = 0;
        while(dvd >= dvs) {
            long long temp = dvs;
            long long multiple = 1;
            while(dvd >= (temp<<1)) {
                temp <<= 1;
                multiple <<= 1;
            }
            dvd -= temp;
            ans += multiple;
        }
        return sign == 1 ? ans : (-ans);
    }
};

你可能感兴趣的:(Leecode)