Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Count of numbers having only one unset bit in a range [L,R]
Next article icon

Count of numbers having only one unset bit in a range [L,R]

Last Updated : 17 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two integers L and R, the task is to count the numbers having only one unset bit in the range [L, R].

Examples:

Input: L = 4, R = 9
Output: 2
Explanation:
The binary representation of all numbers in the range [4, 9] are 
4 = (100)2 
5 = (101)2 
6 = (110)2 
7 = (111)2 
8 = (1000)2 
9 = (1001)2 
Out of all the above numbers, only 5 and 6 have exactly one unset bit.
Therefore, the required count is 2.

Input: L = 10, R = 13
Output: 2
Explanation:
The binary representations of all numbers in the range [10, 13] 
10 = (1010)2 
11 = (1011)2 
12 = (1100)2 
13 = (1101)2 
Out of all the above numbers, only 11 and 13 have exactly one unset bit. 
Therefore, the required count is 2.

Naive Approach: The simplest approach is to check every number in the range [L, R] whether it has exactly one unset bit or not. For every such number, increment the count. After traversing the entire range, print the value of count.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to count numbers in the range // [l, r] having exactly one unset bit int count_numbers(int L, int R) {     // Stores the required count     int ans = 0;      // Iterate over the range     for (int n = L; n <= R; n++) {          // Calculate number of bits         int no_of_bits = log2(n) + 1;          // Calculate number of set bits         int no_of_set_bits             = __builtin_popcount(n);          // If count of unset bits is 1         if (no_of_bits                 - no_of_set_bits             == 1) {              // Increment answer             ans++;         }     }      // Return the answer     return ans; }  // Driver Code int main() {     int L = 4, R = 9;      // Function Call     cout << count_numbers(L, R);      return 0; } 
Java
// Java program for the above approach import java.util.*; class GFG{  // Function to count numbers in the range // [l, r] having exactly one unset bit static int count_numbers(int L,                           int R) {     // Stores the required count     int ans = 0;      // Iterate over the range     for (int n = L; n <= R; n++)      {         // Calculate number of bits         int no_of_bits = (int) (Math.log(n) + 1);          // Calculate number of set bits         int no_of_set_bits = Integer.bitCount(n);          // If count of unset bits is 1         if (no_of_bits - no_of_set_bits == 1)          {             // Increment answer             ans++;         }     }      // Return the answer     return ans; }  // Driver Code public static void main(String[] args) {     int L = 4, R = 9;      // Function Call     System.out.print(count_numbers(L, R)); } }  // This code is contributed by Rajput-Ji  
Python3
# Python3 program for the above approach from math import log2  # Function to count numbers in the range # [l, r] having exactly one unset bit def count_numbers(L, R):          # Stores the required count     ans = 0      # Iterate over the range     for n in range(L, R + 1):          # Calculate number of bits         no_of_bits = int(log2(n) + 1)          # Calculate number of set bits         no_of_set_bits = bin(n).count('1')          # If count of unset bits is 1         if (no_of_bits - no_of_set_bits == 1):              # Increment answer             ans += 1      # Return the answer     return ans  # Driver Code if __name__ == '__main__':          L = 4     R = 9      # Function call     print(count_numbers(L, R))  # This code is contributed by mohit kumar 29     
C#
// C# program for the above approach using System;  class GFG{  // Function to count numbers in the range // [l, r] having exactly one unset bit static int count_numbers(int L,                           int R) {          // Stores the required count     int ans = 0;      // Iterate over the range     for(int n = L; n <= R; n++)      {                  // Calculate number of bits         int no_of_bits = (int)(Math.Log(n) + 1);          // Calculate number of set bits         int no_of_set_bits = bitCount(n);          // If count of unset bits is 1         if (no_of_bits - no_of_set_bits == 1)          {                          // Increment answer             ans++;         }     }      // Return the answer     return ans; }  static int bitCount(long x) {     int setBits = 0;     while (x != 0)     {         x = x & (x - 1);         setBits++;     }     return setBits; }  // Driver Code public static void Main(String[] args) {     int L = 4, R = 9;      // Function call     Console.Write(count_numbers(L, R)); } }  // This code is contributed by Amit Katiyar  
JavaScript
<script> // javascript program for the // above approach  // Function to count numbers in the range // [l, r] having exactly one unset bit function count_numbers(L, R) {     // Stores the required count     let ans = 0;       // Iterate over the range     for (let n = L; n <= R; n++)     {         // Calculate number of bits         let no_of_bits = Math.floor(Math.log(n) + 1);           // Calculate number of set bits         let no_of_set_bits = bitCount(n);           // If count of unset bits is 1         if (no_of_bits - no_of_set_bits == 1)         {             // Increment answer             ans++;         }     }       // Return the answer     return ans; }   function bitCount(x) {     let setBits = 0;     while (x != 0)     {         x = x & (x - 1);         setBits++;     }     return setBits; }   // Driver Code      let L = 4, R = 9;       // Function Call     document.write(count_numbers(L, R));   // This code is contributed by avijitmondal1998. </script> 

Output: 
2

Time Complexity: O(N*Log R)
Auxiliary Space: O(1)

Efficient Approach: Since the maximum number of bits is at most log R and the number should contain exactly one zero in its binary representation, fix one position in [0, log R] as the unset bit and set all other bits and increment count if the generated number is within the given range. 
Follow the steps below to solve the problem:

  1. Loop over all possible positions of unset bit, say zero_bit, in the range [0, log R]
  2. Set all bits before zero_bit.
  3. Iterate over the range j = zero_bit + 1 to log R and set the bit at position j and increment count if the number formed is within the range [L, R].
  4. Print the count after the above steps.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to count numbers in the range // [L, R] having exactly one unset bit int count_numbers(int L, int R) {     // Stores the count elements     // having one zero in binary     int ans = 0;      // Stores the maximum number of     // bits needed to represent number     int LogR = log2(R) + 1;      // Loop over for zero bit position     for (int zero_bit = 0;          zero_bit < LogR; zero_bit++) {          // Number having zero_bit as unset         // and remaining bits set         int cur = 0;          // Sets all bits before zero_bit         for (int j = 0; j < zero_bit; j++) {              // Set the bit at position j             cur |= (1LL << j);         }          for (int j = zero_bit + 1;              j < LogR; j++) {              // Set the bit position at j             cur |= (1LL << j);              // If cur is in the range [L, R],             // then increment ans             if (cur >= L && cur <= R) {                 ans++;             }         }     }      // Return ans     return ans; }  // Driver Code int main() {     long long L = 4, R = 9;      // Function Call     cout << count_numbers(L, R);      return 0; } 
Java
// Java program for  // the above approach import java.util.*; class GFG{  // Function to count numbers in the range // [L, R] having exactly one unset bit static int count_numbers(int L, int R) {   // Stores the count elements   // having one zero in binary   int ans = 0;    // Stores the maximum number of   // bits needed to represent number   int LogR = (int) (Math.log(R) + 1);    // Loop over for zero bit position   for (int zero_bit = 0; zero_bit < LogR;             zero_bit++)    {     // Number having zero_bit as unset     // and remaining bits set     int cur = 0;      // Sets all bits before zero_bit     for (int j = 0; j < zero_bit; j++)      {       // Set the bit at position j       cur |= (1L << j);     }      for (int j = zero_bit + 1;              j < LogR; j++)      {       // Set the bit position at j       cur |= (1L << j);        // If cur is in the range [L, R],       // then increment ans       if (cur >= L && cur <= R)        {         ans++;       }     }   }    // Return ans   return ans; }  // Driver Code public static void main(String[] args) {   int L = 4, R = 9;    // Function Call   System.out.print(count_numbers(L, R)); } }  // This code is contributed by shikhasingrajput 
Python3
# Python3 program for # the above approach import  math  # Function to count numbers in the range # [L, R] having exactly one unset bit def count_numbers(L, R):        # Stores the count elements     # having one zero in binary     ans = 0;      # Stores the maximum number of     # bits needed to represent number     LogR = (int)(math.log(R) + 1);      # Loop over for zero bit position     for zero_bit in range(LogR):                # Number having zero_bit as unset         # and remaining bits set         cur = 0;          # Sets all bits before zero_bit         for j in range(zero_bit):                        # Set the bit at position j             cur |= (1 << j);          for j in range(zero_bit + 1, LogR):                        # Set the bit position at j             cur |= (1 << j);              # If cur is in the range [L, R],             # then increment ans             if (cur >= L and cur <= R):                 ans += 1;      # Return ans     return ans;  # Driver Code if __name__ == '__main__':     L = 4;     R = 9;      # Function Call     print(count_numbers(L, R));  # This code is contributed by Rajput-Ji  
C#
// C# program for  // the above approach using System;  public class GFG{  // Function to count numbers in the range // [L, R] having exactly one unset bit static int count_numbers(int L, int R) {   // Stores the count elements   // having one zero in binary   int ans = 0;    // Stores the maximum number of   // bits needed to represent number   int LogR = (int) (Math.Log(R) + 1);    // Loop over for zero bit position   for (int zero_bit = 0; zero_bit < LogR;             zero_bit++)    {     // Number having zero_bit as unset     // and remaining bits set     int cur = 0;      // Sets all bits before zero_bit     for (int j = 0; j < zero_bit; j++)      {       // Set the bit at position j       cur |= (1 << j);     }      for (int j = zero_bit + 1;              j < LogR; j++)      {       // Set the bit position at j       cur |= (1 << j);        // If cur is in the range [L, R],       // then increment ans       if (cur >= L && cur <= R)        {         ans++;       }     }   }    // Return ans   return ans; }  // Driver Code public static void Main(String[] args) {   int L = 4, R = 9;    // Function Call   Console.Write(count_numbers(L, R)); } }    // This code contributed by shikhasingrajput  
JavaScript
<script>  // JavaScript  program for //the above approach  // Function to count numbers in the range // [L, R] having exactly one unset bit function count_numbers(L, R) {   // Stores the count elements   // having one zero in binary   let ans = 0;     // Stores the maximum number of   // bits needed to represent number   let LogR =  (Math.log(R) + 1);     // Loop over for zero bit position   for (let zero_bit = 0; zero_bit < LogR;            zero_bit++)   {     // Number having zero_bit as unset     // and remaining bits set     let cur = 0;       // Sets all bits before zero_bit     for (let j = 0; j < zero_bit; j++)     {       // Set the bit at position j       cur |= (1 << j);     }       for (let j = zero_bit + 1;              j < LogR; j++)     {       // Set the bit position at j       cur |= (1 << j);         // If cur is in the range [L, R],       // then increment ans       if (cur >= L && cur <= R)       {         ans++;       }     }   }     // Return ans   return ans; }   // Driver Code      let L = 4, R = 9;     // Function Call   document.write(count_numbers(L, R));    // This code is contributed by souravghosh0416. </script> 

Output: 
2

Time Complexity: O((log R)2)
Auxiliary Space: O(1)


Next Article
Count of numbers having only one unset bit in a range [L,R]

D

dp82
Improve
Article Tags :
  • Bit Magic
  • Greedy
  • Searching
  • Mathematical
  • Competitive Programming
  • DSA
  • setBitCount
  • binary-representation
Practice Tags :
  • Bit Magic
  • Greedy
  • Mathematical
  • Searching

Similar Reads

    Count of numbers having only 1 set bit in the range [0, n]
    Given an integer n, the task is to count the numbers having only 1 set bit in the range [0, n].Examples: Input: n = 7 Output: 3 Explanation: 000, 001, 010, 011, 100, 101, 110 and 111 are the binary representation of all the numbers upto 7. And there are only 3 numbers ( 001, 010 and 100 ) having onl
    3 min read
    Count numbers in the range [L, R] having only three set bits
    Given an array arr[] of N pairs, where each array element denotes a query of the form {L, R}, the task is to find the count of numbers in the range [L, R], having only 3-set bits for each query {L, R}.Examples:Input: arr[] = {{11, 19}, {14, 19}}Output: 4 2Explanation: Query(11, 19): Numbers in the r
    9 min read
    Count numbers in range [L, R] having K consecutive set bits
    Given three positive integers l, r, and k, the task is to find the count of numbers in the range [l, r] having k consecutive set bits in their binary representation.Examples:Input: l = 4, r = 15, k = 3 Output: 3 Explanation: Numbers whose binary representation contains k=3 consecutive set bits are:
    13 min read
    Count total set bits in all numbers from range L to R
    Given two positive integers L and R, the task is to count the total number of set bits in the binary representation of all the numbers from L to R. Examples: Input: L = 3, R = 5 Output: 5 Explanation: (3)10 = (11)2, (4)10 = (100)2, (5)10 = (101)2 So, Total set bit in range 3 to 5 is 5 Input: L = 10,
    15+ min read
    Count numbers up to N having Kth bit set
    Given two integers N and K, the task is to find the count of numbers up to N having K-th (0-based indexing) bit set. Examples: Input: N = 14, K = 2Output: 7Explanation: The numbers less than equal to 14, having 2nd bit set are 4, 5, 6, 7, 12, 13, and 14. Input: N = 6, K = 1Output: 3Explanation: The
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences