Skip to content
Related Articles

Related Articles

Improve Article

Count of N-bit binary numbers without leading zeros

  • Last Updated : 01 Apr, 2021

Given an integer N, the task is to find the count of N-bit binary numbers without leading zeros.
Examples: 
 

Input: N = 2 
Output:
10 and 11 are the only possible binary numbers.
Input: N = 4 
Output:
 

 

Approach: Since the numbers cannot have leading zeros so the left-most bit has to be set to 1. Now for the rest of the N – 1 bits, there are two choices they can either be set to 0 or 1. So, the count of possible numbers will be 2N – 1.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the count
// of possible numbers
int count(int n)
{
    return pow(2, n - 1);
}
 
// Driver code
int main()
{
    int n = 4;
 
    cout << count(n);
 
    return 0;
}

Java




// Java implementation of the approach
class GFG
{
     
    // Function to return the count
    // of possible numbers
    static int count(int n)
    {
        return (int)Math.pow(2, n - 1);
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int n = 4;
     
        System.out.println(count(n));
    }
}
 
// This code is contributed by AnkitRai01

Python3




# Python3 implementation of the approach
 
# Function to return the count
# of possible numbers
def count(n):
    return pow(2, n - 1)
 
# Driver code
n = 4
 
print(count(n))
 
# This code is contributed by mohit kumar

C#




// C# implementation of the approach
using System;
     
class GFG
{
    // Function to return the count
    // of possible numbers
    static int count(int n)
    {
        return (int)Math.Pow(2, n - 1);
    }
     
    // Driver code
    public static void Main (String[] args)
    {
        int n = 4;
     
        Console.WriteLine(count(n));
    }
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
 
 
// JavaScript implementation of the approach
 
// Function to return the count
// of possible numbers
function count(n)
{
    return Math.pow(2, n - 1);
}
 
// Driver code
var n = 4;
document.write(count(n));
 
 
</script>
Output: 
8

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :