Skip to content

Latest commit

 

History

History
22 lines (21 loc) · 576 Bytes

29. Divide Two Integers.md

File metadata and controls

22 lines (21 loc) · 576 Bytes
class Solution {
public:
    int divide(int dividend, int divisor) {
        if (dividend == INT_MIN && divisor == -1) return INT_MAX; 
        long m = labs(dividend), n = labs(divisor), ans = 0;
        int sign = (dividend < 0) ^ (divisor < 0) ? - 1 : 1;
        if (n == 1) return sign == 1 ? m : -m;
        while (m >= n) {
            long t = n, cnt = 1;
            while (m >= (t << 1)) {
                t <<= 1;
                cnt <<= 1;
            }
            ans += cnt;
            m -= t;
        }
        return sign == 1 ? ans : -ans;
    }
};