Sum of decimals that are binary representations of first N natural numbers
Input: N = 3
The Binary Representation of 1 is 01.
The Binary Representation of 2 is 10.
The Binary Representation of 3 is 11.
Therefore, required sum = 01 + 10 + 11 = 22.
Input: N = 5
Naive Approach: The simplest approach to solve the problem is to iterate a loop over the range [1, N] and in each iteration convert the current number to its binary representation and add it to the overall sum. After adding all the numbers, print the sum as the result.
Time Complexity: O(N * log(N))
Auxiliary Space: O(32)
Efficient Approach: The above approach can also be optimized by finding the contribution of numbers not having the same most significant bit (MSB) position as N and then find the contribution by the MSB of the rest of the numbers. Follow the steps to solve the problem:
- Initialize a variable, say ans as 0 to store the sum of all the numbers in the binary representation of first N natural numbers.
- Iterate until the value of N is at least 0, and perform the following steps:
- Store the MSB position of the number N in a variable X and store the value of 2(X – 1) in a variable, say A.
- Initialize a variable, say cur as 0 to store the contribution of numbers not having the same MSB position as N.
- Iterate over the range [1, X], and in each iteration, add A to the variable cur and then multiply A by 10.
- After the above steps, add the value of cur to ans and store the remaining elements in variable rem as (N – 2X + 1).
- Add the contribution by the MSB of the rest of the numbers by adding (rem * 10X) to the ans.
- Update the value of N to (rem – 1) for the next iteration.
- After completing the above steps, print the value of ans as the 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 mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.