Count of integers up to N which represent a Binary number

Given an integer N, the task is to count every number i from 1 to N (both inclusive) such that i is a binary representation of some integer where N can be any value within the range[1, 109]

Examples:

Input: N = 100
Output: 4
Explanation: Valid integers are 1, 10, 11, 100

Input: N = 20
Output: 3
Explanation: Valid integers are 1, 10, 11

Naive approach: Since maximum number of digits in N can be 10 so store every binary combination of 10 digits and then use Binary search or upper_bound to check the largest integer in the given range of N.



Time Complexity: O(MAX + log(MAX)) where MAX = 1024 (210)

Efficient approach: We can observe that for any value of N, the maximum number of such possible representations is 2count of digits of N – 1. Hence, we need to follow the following steps:

  • Extract digits of N from right to left and store the position of the current digit in a variable ctr.
  • If the current digit exceeds 1, it means that maximum possible representations using ctr digits can be obtained. Thus, set answer equal to 2ctr – 1.
  • Otherwise, if the current digit is 1, then add 2ctr – 1 to the answer obtained so far.
  • The final value obtained after traversing all the digits gives the answer.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to count the
// number of integers upto N
// which are of the form of
// binary representations
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the count
int countBinaries(int N)
{
  
    int ctr = 1;
    int ans = 0;
    while (N > 0) {
  
        // If the current last
        // digit is 1
        if (N % 10 == 1) {
  
            // Add 2^(ctr - 1) possible
            // integers to the answer
            ans += pow(2, ctr - 1);
        }
  
        // If the current digit exceeds 1
        else if (N % 10 > 1) {
  
            // Set answer as 2^ctr - 1
            // as all possible binary
            // integers with ctr number
            // of digits can be obtained
            ans = pow(2, ctr) - 1;
        }
  
        ctr++;
        N /= 10;
    }
  
    return ans;
}
// Driver Code
int main()
{
  
    int N = 20;
    cout << countBinaries(N);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count the number 
// of integers upto N which are of 
// the form of binary representations
import java.util.*;
class GFG{
  
// Function to return the count
static int countBinaries(int N)
{
    int ctr = 1;
    int ans = 0;
    while (N > 0
    {
          
        // If the current last
        // digit is 1
        if (N % 10 == 1)
        {
  
            // Add 2^(ctr - 1) possible
            // integers to the answer
            ans += Math.pow(2, ctr - 1);
        }
  
        // If the current digit exceeds 1
        else if (N % 10 > 1)
        {
  
            // Set answer as 2^ctr - 1
            // as all possible binary
            // integers with ctr number
            // of digits can be obtained
            ans = (int) (Math.pow(2, ctr) - 1);
        }
        ctr++;
        N /= 10;
    }
    return ans;
}
  
// Driver Code
public static void main(String[] args)
{
    int N = 20;
    System.out.print(countBinaries(N));
}
}
  
// This code is contributed by amal kumar choubey

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count the
# number of integers upto N
# which are of the form of
# binary representations
from math import *
  
# Function to return the count
def countBinaries(N):
      
    ctr = 1
    ans = 0
      
    while (N > 0):
          
        # If the current last
        # digit is 1
        if (N % 10 == 1):
              
            # Add 2^(ctr - 1) possible
            # integers to the answer
            ans += pow(2, ctr - 1)
  
        # If the current digit exceeds 1
        elif (N % 10 > 1):
              
            # Set answer as 2^ctr - 1
            # as all possible binary
            # integers with ctr number
            # of digits can be obtained
            ans = pow(2, ctr) - 1
  
        ctr += 1
        N //= 10
  
    return ans
  
# Driver Code
if __name__ == '__main__':
      
    N = 20
      
    print(int(countBinaries(N)))
  
# This code is contributed by Bhupendra_Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count the number 
// of integers upto N which are of 
// the form of binary representations
using System;
  
class GFG{
  
// Function to return the count
static int countBinaries(int N)
{
    int ctr = 1;
    int ans = 0;
    while (N > 0) 
    {
          
        // If the current last
        // digit is 1
        if (N % 10 == 1)
        {
              
            // Add 2^(ctr - 1) possible
            // integers to the answer
            ans += (int)Math.Pow(2, ctr - 1);
        }
  
        // If the current digit exceeds 1
        else if (N % 10 > 1)
        {
  
            // Set answer as 2^ctr - 1
            // as all possible binary
            // integers with ctr number
            // of digits can be obtained
            ans = (int)(Math.Pow(2, ctr) - 1);
        }
        ctr++;
        N /= 10;
    }
    return ans;
}
  
// Driver Code
public static void Main(String[] args)
{
    int N = 20;
    Console.Write(countBinaries(N));
}
}
  
// This code is contributed by amal kumar choubey

chevron_right


Output:

3

Time Complexity: O(M2) where M is the count of digits in N
Auxilary Space: O(1)

Optimization: The above approach can be optimized by pre-computing the powers of 2 up to M (count of digits up to M of N) by the help of a prefix product array.

Below is the implementation of the optimized solution:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to count the
// number of integers upto N
// which are of the form of
// binary representations
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the count
int countBinaries(int N)
{
    // PreCompute and store
    // the powers of 2
    vector<int> powersOfTwo(11);
  
    powersOfTwo[0] = 1;
    for (int i = 1; i < 11; i++) {
        powersOfTwo[i] 
= powersOfTwo[i - 1] 
* 2;
    }
  
    int ctr = 1;
    int ans = 0;
    while (N > 0) {
  
        // If the current last
        // digit is 1
        if (N % 10 == 1) {
  
            // Add 2^(ctr - 1) possible
            // integers to the answer
            ans += powersOfTwo[ctr - 1];
        }
  
        // If the current digit exceeds 1
        else if (N % 10 > 1) {
  
            // Set answer as 2^ctr - 1
            // as all possible binary
            // integers with ctr number
            // of digits can be obtained
            ans = powersOfTwo[ctr] - 1;
        }
  
        ctr++;
        N /= 10;
    }
  
    return ans;
}
// Driver Code
int main()
{
  
    int N = 20;
    cout << countBinaries(N);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count the number of 
// integers upto N which are of the 
// form of binary representations
import java.util.*;
  
class GFG{
  
// Function to return the count
static int countBinaries(int N)
{
      
    // PreCompute and store
    // the powers of 2
    Vector<Integer> powersOfTwo = new Vector<Integer>(11);
    powersOfTwo.add(1);
      
    for(int i = 1; i < 11; i++)
    {
       powersOfTwo.add(powersOfTwo.get(i - 1) * 2); 
    }
  
    int ctr = 1;
    int ans = 0;
    while (N > 0)
    {
  
        // If the current last
        // digit is 1
        if (N % 10 == 1)
        {
  
            // Add 2^(ctr - 1) possible
            // integers to the answer
            ans += powersOfTwo.get(ctr - 1);
        }
  
        // If the current digit exceeds 1
        else if (N % 10 > 1
        {
  
            // Set answer as 2^ctr - 1
            // as all possible binary
            // integers with ctr number
            // of digits can be obtained
            ans = powersOfTwo.get(ctr) - 1;
        }
        ctr++;
        N /= 10;
    }
    return ans;
}
  
// Driver Code
public static void main(String[] args)
{
    int N = 20;
    System.out.print(countBinaries(N));
}
}
  
// This code is contributed by amal kumar choubey

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count the number of 
// integers upto N which are of the 
// form of binary representations
using System;
using System.Collections.Generic;
class GFG{
  
// Function to return the count
static int countBinaries(int N)
{
      
    // PreCompute and store
    // the powers of 2
    List<int> powersOfTwo = new List<int>();
    powersOfTwo.Add(1);
      
    for(int i = 1; i < 11; i++)
    {
        powersOfTwo.Add(powersOfTwo[i - 1] * 2); 
    }
  
    int ctr = 1;
    int ans = 0;
    while (N > 0)
    {
  
        // If the current last
        // digit is 1
        if (N % 10 == 1)
        {
  
            // Add 2^(ctr - 1) possible
            // integers to the answer
            ans += powersOfTwo[ctr - 1];
        }
  
        // If the current digit exceeds 1
        else if (N % 10 > 1) 
        {
  
            // Set answer as 2^ctr - 1
            // as all possible binary
            // integers with ctr number
            // of digits can be obtained
            ans = powersOfTwo[ctr] - 1;
        }
        ctr++;
        N /= 10;
    }
    return ans;
}
  
// Driver Code
static public void Main ()
{
    int N = 20;
    Console.Write(countBinaries(N));
}
}
  
// This code is contributed by ShubhamCoder

chevron_right


Output:

3

Time Complexity: O(M)
Auxilary Space: O(M)

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.