LeetCode "Divide Two Integers"

A very interesting numeric problem. It involves a lot tricks.

Linear search (by +-) is not feasible - too slow. So binary search is a good idea. Also please take special care of integer overflow!

class Solution {
public:
    unsigned long _divide(unsigned long tgt, unsigned long adiv, unsigned long start)
    {
        if ((tgt - start) <= adiv) return (tgt - start) / adiv;
        
        unsigned n = 0;
        while (((adiv << n) + start) < tgt) n++;

        return (1 << (n - 1)) + _divide(tgt, adiv, (adiv << (n - 1)) + start);
    }
    int divide(int dividend, int divisor) {
        if (dividend == 0) return 0;
        unsigned long adend = abs(dividend);
        unsigned long adiv = abs(divisor);
        int iNeg = 0;
        if ((dividend < 0 && divisor > 0) ||
            (dividend > 0 && divisor < 0))
        {
            iNeg = -1;
        }
        else
        {
            iNeg = 1;
        }
        
        if (adiv == 1)    return adend * iNeg;

        unsigned long ret = _divide(adend, adiv, 0);
        
        return ret * iNeg;
    }
};
原文地址:https://www.cnblogs.com/tonix/p/3875211.html