Count of numbers having only one unset bit in a range [L,R]
Last Updated :
17 May, 2021
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>
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:
- Loop over all possible positions of unset bit, say zero_bit, in the range [0, log R]
- Set all bits before zero_bit.
- 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].
- 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>
Time Complexity: O((log R)2)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn 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
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA 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
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem