![]() |
VOOZH | about |
Given two integers l and r, find the count of numbers x such that:
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
Table of Content
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 exactly3set 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.
l to r3, increment the result 5
A number having exactly
3set bits can be formed by choosing any3distinct bit positions. Since along longinteger has at most63usable 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)
3 set bits using:(1LL<<i)β
ββ£β
β(1LL<<j)β
ββ£β
β(1LL<<k)(1LL << i) lowerBound() for first index having value >= l and upperBound() for first index having value > r5