FastPrepCount Reachable Values by Halving and Decrementing
Problem · Breadth First Search

Count Reachable Values by Halving and Decrementing

Learn this problem
Mediuminfosys logoinfosysNEW GRADOA

Problem 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) → int

Examples

Example 1

num = 6steps = 2return = 5

The reachable values are 6, 5, 3, 4, and 2.

Example 2

num = 0steps = 60return = 1

Halving zero returns zero and decrement is unavailable, so only zero is reachable.

Example 3

num = 5steps = 0return = 1

With 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.

More infosys problems

drafts saved locally
public int countReachableValues(int num, int steps) {
    // Write your code here.
}
num6
steps2
expected5
checking account