#754
Reach a Number
specialist · 985 · lc medium +32 · verified · 44.7% accepted · 1,936 likes · top 27%
Description
Starting at position 0 on an infinite number line, you must reach target. On the ith move (1-indexed) you travel exactly i steps either left or right. Return the minimum total number of moves needed to land exactly on target.
Example 1:
Input: target = 2
Output: 3
Explanation:
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
Example 2:
Input: target = 3
Output: 2
Explanation:
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
Code
1
2
3