Posts Count Total Set Bits Till N
Post
Cancel

Count Total Set Bits Till N

PROBLEM DESCRIPTION

You are given a number N. Find the total number of setbits in the numbers from 1 to N.

geeksforgeeks

SOLUTION

snapshot

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution{
    
    static int countBits(int A){
        
        //base case
        if(A == 0) return 0;

        //highest power of 2, which is less than or equal to A
        long x = logBase2(A);

        //number of 1s present in each bit position = 2^x / 2
        long numerOfOnesInEachPosition = (1<<x)/2;

        //how many positions have any set bits? 
        long totalNumberOfPositions = x;

        //all the remaining numbers from 2^x to A will have set bit in its MSB
        long msbContributionForRemainingNumbers = (A - (1<<x) + 1);

        //current total = (total number of set bits upto 2^x - 1) + (set bits in the MSB in the remaining numbers)
        long currentTotal = (numerOfOnesInEachPosition * totalNumberOfPositions) + msbContributionForRemainingNumbers;

        //if we carefully observe, (A / 2^x) is now a sub-problem. So, calculate that using recursion and add that to the currentTotal
        long contributionByRemaining = countBits( A - (1<<x) );

        return (int)(currentTotal + contributionByRemaining); 
    }
    
    public static long logBase2(long n){

        long c = 0;

        while(n > 1){
            c++;
            n = n/2;
        }

        return c;

    }
}
This post is licensed under CC BY 4.0 by the author.