返回介绍

solution / 0700-0799 / 0754.Reach a Number / README_EN

发布于 2024-06-17 01:03:34 字数 3245 浏览 0 评论 0 收藏 0

754. Reach a Number

中文文档

Description

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

 

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

 

Constraints:

  • -109 <= target <= 109
  • target != 0

Solutions

Solution 1

class Solution:
  def reachNumber(self, target: int) -> int:
    target = abs(target)
    s = k = 0
    while 1:
      if s >= target and (s - target) % 2 == 0:
        return k
      k += 1
      s += k
class Solution {
  public int reachNumber(int target) {
    target = Math.abs(target);
    int s = 0, k = 0;
    while (true) {
      if (s >= target && (s - target) % 2 == 0) {
        return k;
      }
      ++k;
      s += k;
    }
  }
}
class Solution {
public:
  int reachNumber(int target) {
    target = abs(target);
    int s = 0, k = 0;
    while (1) {
      if (s >= target && (s - target) % 2 == 0) return k;
      ++k;
      s += k;
    }
  }
};
func reachNumber(target int) int {
  if target < 0 {
    target = -target
  }
  var s, k int
  for {
    if s >= target && (s-target)%2 == 0 {
      return k
    }
    k++
    s += k
  }
}
/**
 * @param {number} target
 * @return {number}
 */
var reachNumber = function (target) {
  target = Math.abs(target);
  let [s, k] = [0, 0];
  while (1) {
    if (s >= target && (s - target) % 2 == 0) {
      return k;
    }
    ++k;
    s += k;
  }
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文