二进制中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的个数
标题来源:http://hbruida.cn/article/jgdisp.html