• HackerRank


    This one is marked as "Advanced".. i don't tink so, not that hard if you can visualize all the bits from a to b. Two key points here:

    1. Say both a and b are positive, bits form an interesting pattern vertically - all bit[i] of all numbers
    2. negative numbers, count(a) = 32 - count(1 - a)

    The above observation leads to this code:

    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    
    long long _calc(long long a, long long b)
    {
        int bb = b;
        int pc = 1, sz = 2;
        long long ttl = 0;
        while (bb)
        {
            int sa = a / sz;
            int sb = b / sz;
            long long cnt = (long long)(sb - sa + 1) * (long long)pc;
    
            int ra = a % sz;
            if (ra > pc)
                cnt -= std::max(ra - pc, 0);
            int rb = b % sz;
            if (rb < sz - 1)
                cnt -= std::min(pc, sz - rb - 1);
    
            ttl += cnt;
    
            //    Move on
            bb >>= 1;
            pc *= 2;
            sz *= 2;
        }
    
        return ttl;
    }
    
    long long calc(long long a, long long b)
    {
        long long cnt = 0;
    
        //    negative
        int na, nb;
        if (a < 0)
        {
            na = a; nb = std::min((long long)-1, b);
            long long aa = -(nb + 1);
            long long bb = -(na + 1);
            long long ret = _calc(aa, bb);
            cnt = (long long)(bb - aa + 1) * 32 - ret;
        }
    
        long long pa, pb;
        if (b >= 0)
        {
            pa = std::max(a, (long long)0);
            pb = b;
            cnt += _calc(pa, pb);
        }
        return cnt;
    }
    
    int main() 
    {
        int t; cin >> t;
        while (t--)
        {
            long long a, b; cin >> a >> b;
            auto r = calc(a, b);
            cout << r << endl;
        }
        return 0;
    }
  • 相关阅读:
    用上帝视角来看待组件的设计模式
    npm和package.json那些不为常人所知的小秘密
    四步走查智能硬件异常Case
    PorterDuffXfermode 图像混合技术在漫画APP中的应用
    发布流程进化史
    二叉搜索树的操作集
    02-线性结构1 两个有序链表序列的合并
    07-图6 旅游规划
    树的同构
    线性结构4 Pop Sequence
  • 原文地址:https://www.cnblogs.com/tonix/p/4585077.html
Copyright © 2020-2023  润新知