BIT - Editorial

PROBLEM LINK:

Contest

DIFFICULTY:

CAKEWALK

PROBLEM:

Print sum of set bits of all numbers from 1 to N.

QUICK EXPLANATION:

Simple simulation. For each number we count set bits and add them to the final answer.
To count set bits convert the number to base 2 and count the number of 1s.
Complexity: N log (N)

CODE:

#define sd(n) scanf("%d",&n)
int foo(int p)
{
    int ret=0;
    while(p)ret+=p&1,p/=2;
    return ret;
}
int main()
{
    int t;
    sd(t);
    while(t--)
    {
        int n,ans=0,i;
        sd(n);
        for(i=1; i<=n; i++)
            ans+=foo(i);
        printf("%d\n",ans);
    }
    return 0;
}