LandscapeMi

landscapemi的博客

leetcode :Binary Search: Divide Two Integers(029)

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

If it is overflow, return MAX_INT.


算法

o(nlgn)



typedef long long ll;
class Solution {
public:
    int divide(int dividend, int divisor) {
        ll a = dividend >= 0 ? dividend : -(ll)dividend;
        ll b = divisor >= 0 ? divisor : -(ll)divisor;
        ll result = 0, c = 0;
        bool sign = (dividend > 0 && divisor < 0) ||
            (dividend < 0 && divisor > 0);

        while (a >= b) {
            c = b;
            for (int i = 0; a >= c; i++, c <<= 1) {
                a -= c;
                result += (1<<i);
            }
        }
        if (sign) {
            return max((ll)INT_MIN, -result);
        } else {
            return min((ll)INT_MAX, result);
        }
    }
};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mijian1207mijian/article/details/52346195
个人分类: leetcode(c++)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭