Find the number obtained by concatenating binary representations of all numbers up to N
Given an integer N, the task is to find the decimal value of the binary string formed by concatenating the binary representations of all numbers from 1 to N sequentially.
Hey geek! It's time to become a success story instead of reading them. Check out our most renowned DSA Self Paced Course, now at a student-friendly price and become industry ready. And if you are looking for a more complete interview preparation resource, check out Complete Interview Preparation Course that will prepare you for the SDE role of your dreams!
Feeling prepared enough for your interview? Test your skills with our Test Series that will help you prepare for top companies like Amazon, Microsft, TCS, Wipro, Google and many more!
Input: N = 12
Explanation: The concatenation results in “1101110010111011110001001101010111100”. The equivalent decimal value is 118505380540.
Input: N = 3
Explanation: In binary, 1, 2, and 3 correspond to “1”, “10”, and “11”. Their concatenation results in “11011”, which corresponds to the decimal value of 27.
Approach: The idea is to iterate over the range [1, N]. For every ith number, concatenate the binary representation of the number i using the Bitwise XOR property. Follow the steps below to solve the problem:
- Initialize two variables, l, and ans with 0, where l stores the current position of the bit in the final binary string of any ith number and ans will store the final answer.
- Iterate from i = 1 to N + 1.
- If (i & ( i – 1 )) is equal to 0, then simply increment the value of l by 1, where & is the Bitwise AND operator.
- After that, the left shift ans by l and then bitwise OR the result with i.
- After and traversing, print ans as the answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)