C++ code, Binary Search, get rid of corner cases


  • 0
    J
    class Solution {
    public:
        int divide(int dividend, int divisor) {
            if(dividend==0)
                return 0;
            bool positive = ((dividend>0 && divisor>0) || (dividend<0 && divisor<0))? true : false;
            long dn = dividend>0? dividend : 0-(long)dividend;
            long dr = divisor>0? divisor : 0-(long)divisor;
            long result = 0, residual = dn;
            while(dr<=residual) {
                long times = 1;
                long re = dr;
                while(re+re<=residual) {
                    times += times;
                    re += re;
                }
                result += times;
                residual -= re;
            }
            return positive? (int)min((long)INT32_MAX,result) : (int)max((long)INT32_MIN,0-result);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.