Reach A Number Problem
Description
LeetCode Problem 754.
You are standing at position 0 on an infinite number line. There is a destination at position target.
You can make some number of moves numMoves so that:
- On each move, you can either go left or right.
- During the i^th move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction.
Given the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to reach the destination.
Example 1:
1
2
3
4
5
6
Input: target = 2
Output: 3
Explanation:
On the 1^st move, we step from 0 to 1 (1 step).
On the 2^nd move, we step from 1 to -1 (2 steps).
On the 3^rd move, we step from -1 to 2 (3 steps).
Example 2:
1
2
3
4
5
Input: target = 3
Output: 2
Explanation:
On the 1^st move, we step from 0 to 1 (1 step).
On the 2^nd move, we step from 1 to 3 (2 steps).
Constraints:
- -10^9 <= target <= 10^9
- target != 0
Sample C++ Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int reachNumber(int target) {
target = abs(target);
int sum = 0, moves = 0, i = 1;
while (true) {
sum += i;
i ++;
moves ++;
if (sum == target)
return moves;
if (sum > target && (sum - target) % 2 == 0)
return moves;
}
return moves;
}
};