LeetCode 0029 - Divide Two Integers

2021-08-11 10:33:36 浏览数 (1)

Divide Two Integers

Desicription

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

If it is overflow, return MAX_INT.

Solution

代码语言:javascript复制
class Solution {
public:
    int divide(int dividend, int divisor) {
        if(!divisor || (dividend == INT_MIN && divisor == -1))
            return INT_MAX;
        int flag = ((dividend < 0) ^ (divisor < 0))?-1:1;
        long long m = abs((long long)dividend);
        long long n = abs((long long)divisor);
        int res = 0;
        while(m >= n){
            long long t = n;
            long long p = 1;
            while((t << 1) <= m){
                t <<= 1;
                p <<= 1;
            }
            m -= t;
            res  = p;
        }
        return flag*res;
    }
};

0 人点赞