Reach a Number

medium math binary search

Problem

Starting at 0 on a number line, on the i-th move you take exactly i steps left or right. Return the minimum number of moves required to reach the integer target.

Inputtarget=2
Output3
Moves are -1, +2, +1 totalling 2 in 3 steps with even overshoot parity.

def reachNumber(target):
    target = abs(target)
    k = 0; total = 0
    while total < target or (total - target) % 2:
        k += 1
        total += k
    return k
function reachNumber(target) {
  target = Math.abs(target);
  let k = 0, total = 0;
  while (total < target || (total - target) % 2 !== 0) {
    k++;
    total += k;
  }
  return k;
}
class Solution {
  public int reachNumber(int target) {
    target = Math.abs(target);
    int k = 0; long total = 0;
    while (total < target || (total - target) % 2 != 0) {
      k++;
      total += k;
    }
    return k;
  }
}
class Solution {
public:
  int reachNumber(int target) {
    target = abs(target);
    int k = 0; long total = 0;
    while (total < target || (total - target) % 2 != 0) {
      k++;
      total += k;
    }
    return k;
  }
};
Time: O(sqrt(target)) Space: O(1)