Open In App

Count of binary strings of given length consisting of at least one 1

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
1 Like
Like
Report

Given an integer N, the task is to print the number of binary strings of length N which at least one '1'.

Examples:  

Input:
Output:
Explanation: 
"01", "10" and "11" are the possible strings

Input:
Output:
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++
Java Python3 C# JavaScript

Output: 
3

 

Time Complexity: O(N) 
Auxiliary Space: O(1)
 


Article Tags :

Explore