zoukankan      html  css  js  c++  java
  • LeetCode Divide Two Integers

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

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

    参考:

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

  • 相关阅读:
    HDU 3949 XOR
    [JXOI2018]游戏
    树状数组 Binary Indexed Tree/Fenwick Tree
    Java 多线程编程
    概率算法
    最长回文子串 Manacher算法
    动态规划-最长上升子序列 LIS
    流水作业调度
    多机调度问题
    A*搜索算法
  • 原文地址:https://www.cnblogs.com/lailailai/p/3669490.html
Copyright © 2011-2022 走看看