Count of Binary Digit numbers smaller than N
Last Updated :
16 Oct, 2022
Given a limit N, we need to find out the count of binary digit numbers which are smaller than N. Binary digit numbers are those numbers that contain only 0 and 1 as their digits, like 1, 10, 101, etc are binary digit numbers.
Examples:
Input : N = 200
Output : 7
Count of binary digit number smaller than N is 7,
enumerated below,
1, 10, 11, 110, 101, 100, 111
One simple way to solve this problem is to loop from 1 to N and check each number whether it is a binary digit number or not. If it is a binary digit number, increase the count of such numbers, but this procedure will take O(N) time. We can do better, as we know that the count of such numbers will be much smaller than N. We can iterate over binary digit numbers only and check whether generated numbers are smaller than N or not.
In the code below, the BFS-like approach is implemented to iterate over only binary digit numbers. We start with 1 and each time we will push (t*10) and (t*10 + 1) into the queue where t is the popped element. If t is a binary digit number, then (t*10) and (t*10 + 1) will also number, so we will iterate over these numbers by only using the queue. We will stop pushing elements in the queue when popped number crosses the N.
C++
// C++ program to count all binary digit
// numbers smaller than N
#include <bits/stdc++.h>
using namespace std;
// method returns count of binary digit
// numbers smaller than N
int countOfBinaryNumberLessThanN(int N)
{
// queue to store all intermediate binary
// digit numbers
queue<int> q;
// binary digits start with 1
q.push(1);
int cnt = 0;
int t;
// loop until we have element in queue
while (!q.empty())
{
t = q.front();
q.pop();
// push next binary digit numbers only if
// current popped element is N
if (t <= N)
{
cnt++;
// uncomment below line to print actual
// number in sorted order
// cout << t << " ";
q.push(t * 10);
q.push(t * 10 + 1);
}
}
return cnt;
}
// Driver code to test above methods
int main()
{
int N = 200;
cout << countOfBinaryNumberLessThanN(N);
return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;
// java program to count all binary digit
// numbers smaller than N
public class GFG {
// method returns count of binary digit
// numbers smaller than N
static int countOfBinaryNumberLessThanN(int N) {
// queue to store all intermediate binary
// digit numbers
Queue<Integer> q = new LinkedList<>();
// binary digits start with 1
q.add(1);
int cnt = 0;
int t;
// loop until we have element in queue
while (q.size() > 0) {
t = q.peek();
q.remove();
// push next binary digit numbers only if
// current popped element is N
if (t <= N) {
cnt++;
// uncomment below line to print actual
// number in sorted order
// cout << t << " ";
q.add(t * 10);
q.add(t * 10 + 1);
}
}
return cnt;
}
// Driver code to test above methods
static public void main(String[] args) {
int N = 200;
System.out.println(countOfBinaryNumberLessThanN(N));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to count all binary digit
# numbers smaller than N
from collections import deque
# method returns count of binary digit
# numbers smaller than N
def countOfBinaryNumberLessThanN(N):
# queue to store all intermediate binary
# digit numbers
q = deque()
# binary digits start with 1
q.append(1)
cnt = 0
# loop until we have element in queue
while (q):
t = q.popleft()
# push next binary digit numbers only if
# current popped element is N
if (t <= N):
cnt = cnt + 1
# uncomment below line to print actual
# number in sorted order
q.append(t * 10)
q.append(t * 10 + 1)
return cnt
# Driver code to test above methods
if __name__=='__main__':
N = 200
print(countOfBinaryNumberLessThanN(N))
# This code is contributed by
# Sanjit_Prasad
C#
// C# program to count all binary digit
// numbers smaller than N
using System;
using System.Collections.Generic;
class GFG
{
// method returns count of binary digit
// numbers smaller than N
static int countOfBinaryNumberLessThanN(int N)
{
// queue to store all intermediate binary
// digit numbers
Queue<int> q = new Queue<int>();
// binary digits start with 1
q.Enqueue(1);
int cnt = 0;
int t;
// loop until we have element in queue
while (q.Count > 0)
{
t = q.Peek();
q.Dequeue();
// push next binary digit numbers only if
// current popped element is N
if (t <= N)
{
cnt++;
// uncomment below line to print actual
// number in sorted order
q.Enqueue(t * 10);
q.Enqueue(t * 10 + 1);
}
}
return cnt;
}
// Driver code
static void Main()
{
int N = 200;
Console.WriteLine(countOfBinaryNumberLessThanN(N));
}
}
// This code is contributed by mits
PHP
<?php
// PHP program to count all binary digit
// numbers smaller than N
// method returns count of binary digit
// numbers smaller than N
function countOfBinaryNumberLessThanN($N)
{
// queue to store all intermediate
// binary digit numbers
$q = array();
// binary digits start with 1
array_push($q, 1);
$cnt = 0;
$t = 0;
// loop until we have element in queue
while (!empty($q))
{
$t = array_pop($q);
// push next binary digit numbers only
// if current popped element is N
if ($t <= $N)
{
$cnt++;
// uncomment below line to print
// actual number in sorted order
// cout << t << " ";
array_push($q, $t * 10);
array_push($q, ($t * 10 + 1));
}
}
return $cnt;
}
// Driver Code
$N = 200;
echo countOfBinaryNumberLessThanN($N);
// This code is contributed by mits
?>
JavaScript
<script>
// JavaScript program to count all binary digit
// numbers smaller than N
// method returns count of binary digit
// numbers smaller than N
function countOfBinaryNumberLessThanN(N) {
// queue to store all intermediate binary
// digit numbers
var q = [];
// binary digits start with 1
q.push(1);
var cnt = 0;
var t;
// loop until we have element in queue
while (q.length > 0) {
t = q.pop();
// push next binary digit numbers only if
// current popped element is N
if (t <= N) {
cnt++;
// uncomment below line to print actual
// number in sorted order
q.push(t * 10);
q.push(t * 10 + 1);
}
}
return cnt;
}
// Driver code
var N = 200;
document.write(countOfBinaryNumberLessThanN(N) + "<br>");
</script>
Output:
7
Time complexity: O(log10N)
Auxiliary space: O(log10N) for queue q
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read