[LeetCode] Reach a Number

754. Reach a Number

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int reachNumber(int target) {
target = abs(target);
long long n = ceil((-1.0 + sqrt(1+8.0*target)) / 2);
long long sum = n * (n+1) / 2;
if (sum == target) return n;
long long diff = sum - target;
if (!(diff&1)) return n;

return n + (n & 1 ? 2 : 1);

}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/04/PS/LeetCode/reach-a-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.