leetcode-----29. 两数相除

代码

class Solution {
public:
    int divide(int dividend, int divisor) {
        typedef long long LL;
        vector<LL> exp;
        bool is_minus = false;
        if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) is_minus = true;
        LL a = abs((LL)dividend);
        LL b = abs((LL)divisor);
        for (LL i = b; i <= a; i = i + i) {
            exp.push_back(i);
        }
        LL ans = 0;
        for (int i = exp.size() - 1; i >= 0; --i) {
            if (a >= exp[i]) {
                a -= exp[i];
                ans += 1ll << i;
            }
        }
        if (is_minus) ans = -ans;
        if (ans > INT_MAX ||ans < INT_MIN) return INT_MAX;
        return ans;
    }
};
posted @ 2020-06-20 15:46  景云ⁿ  阅读(63)  评论(0编辑  收藏  举报