LeetCode Solutions

754. Reach a Number

Time: $O(\sqrt{\texttt{target}})$

Space: $O(1)$

			

class Solution {
 public:
  int reachNumber(int target) {
    const int newTarget = abs(target);
    int ans = 0;
    int pos = 0;

    while (pos < newTarget)
      pos += ++ans;
    while ((pos - newTarget) & 1)
      pos += ++ans;

    return ans;
  }
};
			

class Solution {
  public int reachNumber(int target) {
    final int newTarget = Math.abs(target);
    int ans = 0;
    int pos = 0;

    while (pos < newTarget)
      pos += ++ans;
    while ((pos - newTarget) % 2 == 1)
      pos += ++ans;

    return ans;
  }
}
			

class Solution:
  def reachNumber(self, target: int) -> int:
    ans = 0
    pos = 0
    target = abs(target)

    while pos < target:
      ans += 1
      pos += ans

    while (pos - target) & 1:
      ans += 1
      pos += ans

    return ans