Count of N-bit binary numbers without leading zeros
Given an integer N, the task is to find the count of N-bit binary numbers without leading zeros.
Examples:
Input: N = 2
Output: 2
10 and 11 are the only possible binary numbers.
Input: N = 4
Output: 8
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++
#include <bits/stdc++.h>
using namespace std;
int count( int n)
{
return pow (2, n - 1);
}
int main()
{
int n = 4;
cout << count(n);
return 0;
}
|
Java
class GFG
{
static int count( int n)
{
return ( int )Math.pow( 2 , n - 1 );
}
public static void main (String[] args)
{
int n = 4 ;
System.out.println(count(n));
}
}
|
Python3
def count(n):
return pow ( 2 , n - 1 )
n = 4
print (count(n))
|
C#
using System;
class GFG
{
static int count( int n)
{
return ( int )Math.Pow(2, n - 1);
}
public static void Main (String[] args)
{
int n = 4;
Console.WriteLine(count(n));
}
}
|
Javascript
<script>
function count(n)
{
return Math.pow(2, n - 1);
}
var n = 4;
document.write(count(n));
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Last Updated :
10 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...