Canna

Monday, 24 September 2018

COUNTING BITS

  • Problem Description

    "Given N, if we write all numbers from 1 to N (both inclusive) in binary what is the count of 1s I have written.
    For example, if N=3,
    I will write down:
    1
    10
    11

    Therefore, a total of 4 ones.

    Input Format:

    First line contains, T, the number of testcases. Each testcase consists of one integer per line denoting N.

    Output Format:

    Print the required answer.

    Constraints:


    1 <= T <= 1000
    1 <= N <= 1000
    "
  • Test Case 1

    Input (stdin)
    1
    
    3
    
    
    Expected Output
    4
  • Test Case 2

    Input (stdin)
    1
    
    7
    
    
    Expected Output
    12
  • Program
  • #include<stdio.h>
    int main()
    {
     int t,n,r,i,x;
     scanf("%d",&t);
     while(t--)
     {
      scanf("%d",&n);
      r=0;
      for(i=1;i<=n;i++)
      {
       x=i;
       while(x>0)
       {
        if(x%2==1)
                        r++;
        x/=2;
       }
      }
      printf("%d\n",r);
     }
     return 0;
    }
    

No comments:

Post a Comment

Note: only a member of this blog may post a comment.