码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Divide Two Integers"

时间:2014-07-29 14:02:08      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   art   div   ar   line   

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;
    }
};

LeetCode "Divide Two Integers",布布扣,bubuko.com

LeetCode "Divide Two Integers"

标签:style   blog   color   io   art   div   ar   line   

原文地址:http://www.cnblogs.com/tonix/p/3875211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!