Count of binary strings of given length consisting of at least one 1
Last Updated :
03 Aug, 2021
Given an integer N, the task is to print the number of binary strings of length N which at least one ‘1’.
Examples:
Input: 2
Output: 3
Explanation:
“01”, “10” and “11” are the possible strings
Input: 3
Output: 7
Explanation:
“001”, “011”, “010”, “100”, “101”, “110” and “111” are the possible strings
Approach:
We can observe that:
Only one string of length N does not contain any 1, the one filled with only 0’s.
Since 2N strings are possible of length N, the required answer is 2N – 1.
Follow the steps below to solve the problem:
- Initialize X = 1.
- Compute upto 2N by performing bitwise left shift on X, N-1 times.
- Finally, print X – 1 as the required answer.
Below is the implementation of our approach:
C++
#include <bits/stdc++.h>
using namespace std;
long count_strings( long n)
{
int x = 1;
for ( int i = 1; i < n; i++) {
x = (1 << x);
}
return x - 1;
}
int main()
{
long n = 3;
cout << count_strings(n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static long count_Strings( long n)
{
int x = 1 ;
for ( int i = 1 ; i < n; i++)
{
x = ( 1 << x);
}
return x - 1 ;
}
public static void main(String[] args)
{
long n = 3 ;
System.out.print(count_Strings(n));
}
}
|
Python3
def count_Strings(n):
x = 1 ;
for i in range ( 1 , n):
x = ( 1 << x);
return x - 1 ;
if __name__ = = '__main__' :
n = 3 ;
print (count_Strings(n));
|
C#
using System;
class GFG{
static long count_Strings( long n)
{
int x = 1;
for ( int i = 1; i < n; i++)
{
x = (1 << x);
}
return x - 1;
}
public static void Main(String[] args)
{
long n = 3;
Console.Write(count_Strings(n));
}
}
|
Javascript
<script>
function count_Strings(n)
{
var x = 1;
for (i = 1; i < n; i++) {
x = (1 << x);
}
return x - 1;
}
var n = 3;
document.write(count_Strings(n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...