Show problems as
Classic problem #754MediumMathBinary Search

Reach a Number

Real-world version: Landing Exactly on the Marker
Tracked in this browser only
Read Reach a Number on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A pointer sits at position 0 on a line of whole numbers. On move number k, counting the first move as one, the pointer travels exactly k places, and each move may be taken to the left or to the right.

Return the fewest moves that leave the pointer sitting exactly on marker.

Examples

Example 1

Input
marker = 4
Output
3

One move right, then one left, then one right lands on the marker after three moves. Two moves cannot manage it, because they land on one place away from the start or three away, never four.

Example 2

Input
marker = -1
Output
1

A single move to the left arrives straight away.

Example 3

Input
marker = 11
Output
5

Four moves all rightward reach ten, one short, and no turning of them can shave a single place off, since turning a move around always shifts the finish by an even amount. Five moves rightward overshoot by four, and turning the second move around takes exactly four back.

Constraints

  • -10^9 <= marker <= 10^9
  • marker != 0

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def reach_number(marker: int) -> int:
Java
public int reachNumber(int marker)