Given an integer N, the task is to find the total number of bits toggled to obtain all numbers from 0 to N sequentially.
Input: N = 5
Let’s represent numbers from 0 to 5 in binary:
000 -> 001 : 1 bit toggled
001 -> 010 : 2 bits toggled
010 -> 011 : 1 bit toggled
011 -> 100 : 3 bits toggled
100 -> 101 : 1 bit toggled
Hence, 8 bits toggled
Input: N = 1
Follow the steps below to solve the problems:
- The following observations need to be made to solve the problem:
The rightmost bit toggles every time.
(000) -> (001) -> (010) -> (011)
So, the contribution of this bit to the count will be N.
The next bit toggles after every 2 numbers.
(000) -> (001) -> (010) -> (011) -> (100)
Hence, the contribution of this bit to the count will be N/2.
- Thus, we can conclude that the i th least significant bit will contribute N/(2 i) to the count of toggles.
- Hence, the sum of N/(2i) where i is in the range [0, log2N], gives the required answer.
- Hence, initialize a variable ans. Add N to ans and update N to N/2. Repeat this process until N becomes 0, to get the final result.
Below is the implementation of the above approach:
Time Complexity: O(log N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.