Given a positive integer N, the task is to find out the sum of all consecutive bit differences from 0 to N.
Note: If the bit length is different for two numbers like(3, 4) then append 0 at the beginning (011, 100).
Input: N = 3
Bit differences of (0, 1) + (1, 2) + (2, 3) = 1 + 2 + 1 = 4.
Input: N = 7
The simplest approach is to compare the two consecutive values within the range bitwise and find out by how many bits both these numbers differ. Add this bit difference to the sum. The final sum thus obtained is the required solution.
Time Complexity: O(N)
Following observations are to be made to optimize the above solution:
- The consecutive bit differences of numbers follow a pattern i.e. every value X which is equal to (2i) has a bit difference of (i + 1) with its previous number and the (2i – 1) numbers above X and (2i – 1) numbers below X follow the same pattern.
- For X = 4 (22), i = 2 has a bit difference is (2 + 1) and the numbers (1, 2, 3) and (5, 6, 7) follow the same bit difference pattern.
For X = 4, the pattern is as follows: NUM BIT Diff 1 1(0, 1) 2 2(1, 2) 3 1(2, 3) 4 3(3, 4) 5 1(4, 5) 6 2(5, 6) 7 1(6, 7)
Follow the steps below to solve the problem:
- For every N, find the nearest number less than or equal to N, which is a power of 2. Say that number is M.
- For all the numbers less than M, the below recursive approach can be used to find out the sum of the consecutive bit differences.
Count(i) = (i + 1) + 2 * Count(i – 1)
where i is the exponent of the nearest power of 2.
- Initialize an array of size 65(0 – based indexing) to store the values obtained while using the recursive function Count(), so that in future, if the same values of Count() are needed, they can be directly obtained without recursively calling the Count() function to save time.
- Repeat the same process for the remaining numbers which are greater than M by using the below formula.
Sum = Sum + (i+1) + Count(i-1)
For N = 10, calculate the sum for the nearest power of 2 that is M = 8, using Count(3) and then repeat the process for remaining numbers greater than 8.
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.