VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-numbers-in-the-range-l-r-having-only-three-set-bits/

⇱ Count numbers in the range [l, r] having only three set bits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count numbers in the range [l, r] having only three set bits

Last Updated : 28 May, 2026

Given two integers l and r, find the count of numbers x such that:

  • l ≀ x ≀ r
  • The binary representation of x contains exactly 3 set bits.

Return the total count of such numbers in the given range.

Examples:

Input: l = 11, r = 19
Output: 4
Explanation: There are 4 such numbers with 3 set bits in range 11 to 19. 11 -> 1011, 13 -> 1101, 14 -> 1110, 19 -> 10011. So answer for this test case is 4.

Input: l = 25, r = 29
Output: 3
Explanation: There are 3 such numbers with 3 set bits in range 25 to 29. 25 -> 11001, 26 -> 11010, 28 -> 11100. So answer for this test case is 3

[Naive Approach] Using Bit Counting – O((r βˆ’ l + 1) Γ— log n) Time and O(1) Space

The idea is to traverse every number in the range [l, r] and count the number of set bits in its binary representation. If a number contains exactly 3 set bits, it is counted in the final answer.
The set bits are counted by repeatedly checking the last bit using (n & 1) and then right-shifting the number.

  • Traverse all numbers from l to r
  • For each number, count set bits in binary representation and If the count equals 3, increment the result

Output
5

[Efficient Approach] Using Precomputation + Binary Search – O(1) Query Time

A number having exactly 3 set bits can be formed by choosing any 3 distinct bit positions. Since a long long integer has at most 63 usable bit positions, all such numbers can be generated beforehand using three nested loops.

After generating all valid numbers:

  • Sort them
  • Use binary search to count how many lie in the range [l, r]

The count is: upperBound(r)βˆ’lowerBound(l)

  • Generate all numbers with exactly 3 set bits using:(1LL<<i)β€…β€Šβˆ£β€…β€Š(1LL<<j)β€…β€Šβˆ£β€…β€Š(1LL<<k)(1LL << i)
  • Store all generated numbers in a array and sort the array
  • Use: lowerBound() for first index having value >= l and upperBound() for first index having value > r
  • Their difference gives the required count

Output
5
Comment