![]() |
VOOZH | about |
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:
(7)10 = (111)2
(14)10 = (1110)2
(15)10 = (1111)2
Therefore, the required output is 3.Input: l = 8, r = 100, k = 3
Output: 27
Table of Content
The idea is to traverse all possible integers in the range [l, r] and for each number, check if binary representation of the number contains k consecutive 1's or not. If true, increment the answer.
3
The idea is to use a digit dynamic programming (Digit DP) approach, where we recursively build numbers from the most significant bit (MSB) to the least significant bit (LSB), considering whether the current number is still constrained to the bounds defined by l or r.
At each step, we have two choices:
- Set the current bit to 0.
- Set the current bit to 1.
We also keep track of additional information in our DP state, like whether we’ve encountered
kconsecutive 1s and whether we are still bound by the upper limit. We break down the problem into subproblems by recursively processing the next bit position and transitioning from one state to another.Each state in DP will be:
- i: Current bit position being processed (from 31 down to 0)
- cnt: Count of consecutive set bits (1s) encountered so far.
- kOne: A boolean that tells us whether we have encountered exactly k consecutive set bits at some point in the number.
- tight: A boolean indicating whether the current number we are constructing is still "tight" (i.e., whether it's still less than or equal to the number being processed - either l or r).
3