Skip to main content

Posts

Showing posts with the label count set bits

Count total set bits [BASIC/IMP]

Question:  Find the sum of all bits from numbers 1 to N. Company: Amazon Input: The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N. Output: Print the sum of all bits. Constraints: 1 ≤ T ≤ 100 1 ≤ N ≤ 1000 Example: Input: 2 4 17 Output: 5 35 Explanation: An easy way to look at it is to consider the number 6: 0|0 0 0|0 1 0|1 0 0|1 1 -|– 1|0 0 1|0 1 1|1 0 CODE: #include <stdio.h> int getCount(int n){     int c=0;     while(n){         n=n&(n-1);         c++;     }     return c; } int main() {     int t,i,n,c;     scanf("%d",&t);     while(t--){         c=0;         scanf("%d",&n);         for(i=1;i<=n;i++){             c+=getCount(i);   ...