Problem · Breadth First Search
Count Reachable Values by Halving and Decrementing
Learn this problemProblem statement
Start from the nonnegative integer num. From any current value you may perform either allowed operation:
- If the value is even, replace it with half of itself.
- If the value is positive, replace it with one less.
For this exercise, assume you may perform at most steps operations. Count the distinct nonnegative values that can appear across all valid operation sequences, including the initial value reached with zero operations.
Function
countReachableValues(num: int, steps: int) → intExamples
Example 1
num = 6steps = 2return = 5The reachable values are 6, 5, 3, 4, and 2.
Example 2
num = 0steps = 60return = 1Halving zero returns zero and decrement is unavailable, so only zero is reachable.
Example 3
num = 5steps = 0return = 1With no operation allowed, only the initial value is counted.
Constraints
0 <= num <= 10^9.0 <= steps <= 60.- The answer fits in a signed 32-bit integer.