二进制中1的个数

#include<bits/stdc++.h>
typedef long long ll;
const ll MO = 1000000007;
int T,bin[63],lens;
ll n,ans,power[63],pre[63],nxt[63];
ll read(){ll x;scanf("%lld",&x);return x;}
int main()
{
    scanf("%d",&T), power[0] = 1;
    for (int i=1; i<=61; i++) power[i] = (power[i-1]<<1)%MO;
    for(int cas=1;cas<=T;cas++)
    {
        n = read(), ans = lens = 0;
        for (ll x=n; x; x>>=1) bin[++lens] = x&1;
        pre[0] = nxt[lens+1] = 0;
        for (int i=1; i<=lens; i++) pre[i] = (pre[i-1]+power[i-1]*bin[i])%MO;
        for (int i=lens; i>=1; i--) nxt[i] = ((nxt[i+1]<<1)+bin[i])%MO;
        for (int i=1; i<=lens; i++)
        {
            if (bin[i]) pre[i-1]++,ans = (ans+pre[i-1])%MO;
            ans = (ans+nxt[i+1]*power[i-1]%MO)%MO;
        }
        // ans为1到n中i的二进制1的个数
        //std::cout<<ans<<'\n';continue;
        ans = (n+1ll)%MO*ans%MO;
        for (int i=1; i<=lens; i++)
        {
            if (bin[i]) ans = (ans+MO-pre[i-1]*pre[i-1]%MO)%MO;
            ans = (ans-nxt[i+1]*power[i-1]%MO*power[i-1]%MO+MO)%MO;
        } 
                //  ans-[i,j]前缀1的个数
        printf("Case #%d: %lld\n",cas,ans);
    }
    return 0;
}

// for(ll i=1;i<=n;i<<=1,++len)
// if(n&i)ans+=n%i+1+(n>>len+1)<<len;
// else ans+=(n>>len+1)<<len;
// i属于 [1,n]内i 的二进制下1的个数 总合
上一篇:冒个泡


下一篇:20201230 python数据类型