二进制中1的个数-成都快上网建站

二进制中1的个数

#include
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<>len+1)<>len+1)<

网页题目:二进制中1的个数
URL链接:http://kswjz.com/article/jgdisp.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流