首页 > 其他 > 详细

LeetCode Divide Two Integers

时间:2014-04-16 23:53:28      阅读:744      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
class Solution {
public:
    int divide(int dividend, int divisor) {
        bool aneg = dividend < 0;
        bool bneg = divisor < 0;
        unsigned int a = dividend;
        unsigned int b = divisor;
        if (aneg) a = ~(a - 1);
        if (bneg) b = ~(b - 1);
        unsigned int oa = a, ob = b;
        if (b > a || a == 0) return 0;

        unsigned int abits = 0, bbits = 0;
        while (a) a>>=1, abits++;
        while (b) b>>=1, bbits++;
        a = oa, b = ob;
        unsigned int a_high_bit = 1<<(abits-1);
        unsigned int mask = a_high_bit;
        for (int i=bbits-1; i>0; i--) {
            mask = a_high_bit | (mask>>1);
        }
        unsigned int res = 0;
        unsigned int r_mask = 1<<(abits - bbits);
        b = b<<(abits - bbits);
        while (r_mask) {
            if ((mask & a) >= (mask & b)) {
                res |= r_mask;
                a = a - b;
            }
            mask = (mask>>1)|a_high_bit;
            r_mask>>=1;
            b>>=1;
        }
        if (aneg^bneg)
            return -res;
        else
            return res;
    }
};
bubuko.com,布布扣

犹记得当年计组的时候手工做过,如果不用long的话,在有符号和无符号之间转换要非常小心

参考:

  http://blog.csdn.net/feiyangyangfei/article/details/9214107

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

LeetCode Divide Two Integers

原文:http://www.cnblogs.com/lailailai/p/3669490.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!