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.
Examples:
Input: N = 12
Output: 118505380540
Explanation: The concatenation results in “1101110010111011110001001101010111100”. The equivalent decimal value is 118505380540.
Input: N = 3
Output: 27
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:
C++
#include <bits/stdc++.h>
using namespace std;
int concatenatedBinary( int n)
{
int l = 0;
int ans = 0;
for ( int i = 1; i < n + 1; i++){
if ((i & (i - 1)) == 0)
l += 1;
ans = ((ans << l) | i);
}
return ans;
}
int main()
{
int n = 3;
cout << (concatenatedBinary(n));
return 0;
}
|
Java
class GFG
{
static int concatenatedBinary( int n)
{
int l = 0 ;
int ans = 0 ;
for ( int i = 1 ; i < n + 1 ; i++){
if ((i & (i - 1 )) == 0 )
l += 1 ;
ans = ((ans << l) | i);
}
return ans;
}
public static void main (String[] args)
{
int n = 3 ;
System.out.println(concatenatedBinary(n));
}
}
|
Python3
def concatenatedBinary(n):
l = 0
ans = 0
for i in range ( 1 , n + 1 ):
if i & (i - 1 ) = = 0 :
l + = 1
ans = ((ans << l) | i)
return (ans)
if __name__ = = '__main__' :
n = 3
print (concatenatedBinary(n))
|
C#
using System;
class GFG
{
static int concatenatedBinary( int n)
{
int l = 0;
int ans = 0;
for ( int i = 1; i < n + 1; i++)
{
if ((i & (i - 1)) == 0)
l += 1;
ans = ((ans << l) | i);
}
return ans;
}
public static void Main ()
{
int n = 3;
Console.WriteLine(concatenatedBinary(n));
}
}
|
Javascript
<script>
function concatenatedBinary(n)
{
var l = 0;
var ans = 0;
for ( var i = 1; i < n + 1; i++){
if ((i & (i - 1)) == 0)
l += 1;
ans = parseInt((ans << l) | i);
}
return ans;
}
var n = 3;
document.write(concatenatedBinary(n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)