754. Reach a Number

LeetCode medium original: C# #csharp #leetcode #math #medium #string
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.

Вы стоите в позиции 0 на бесконечной numberвой прямой. В позиции target находится пункт назначения. Вы можете сделать некоторое количество ходов numMoves так, чтобы: на каждом ходу вы могли пойти либо налево, либо направо. Во время i-го хода (начиная с i == 1 до i == numMoves) вы делаете i шагов в выбранном направлении. given 정수 target, return минимальное количество ходов (т.е. минимальное numMoves), необходимое для достижения пункта назначения.

예제:

Input: target = 2

Output: 3

C# 해법

매칭됨/원본
public class Solution {
    public int ReachTarget(int target) {
        target = Math.Abs(target);
        int position = 0;
        int steps = 0;
        while (position < target || (position - target) % 2 != 0) {
            steps++;
            position += steps;
        }
        return steps;
    }
}

C++ 해법

자동 초안, 제출 전 검토
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int ReachTarget(int target) {
        target = abs(target);
        int position = 0;
        int steps = 0;
        while (position < target || (position - target) % 2 != 0) {
            steps++;
            position += steps;
        }
        return steps;
    }
}

Java 해법

매칭됨/원본
public class Solution {
    public int reachTarget(int target) {
        target = Math.abs(target);
        int position = 0;
        int steps = 0;
        while (position < target || (position - target) % 2 != 0) {
            steps++;
            position += steps;
        }
        return steps;
    }

JavaScript 해법

매칭됨/원본
function reachTarget(target) {
    target = Math.abs(target);
    let position = 0;
    let steps = 0;
    while (position < target || (position - target) % 2 !== 0) {
        steps += 1;
        position += steps;
    }
    return steps;
}

Python 해법

매칭됨/원본
def reachTarget(target):
    target = abs(target)
    position = 0
    steps = 0
    while position < target or (position - target) % 2 != 0:
        steps += 1
        position += steps
    return steps

Go 해법

매칭됨/원본
package main

import (
    "fmt"
    "math"
)

func reachTarget(target int) int {
    target = int(math.Abs(float64(target)))
    position := 0
    steps := 0
    for position < target || (position - target) % 2 != 0 {
        steps++
        position += steps
    }
    return steps
}

Algorithm

Инициализируйте переменную для текущей позиции (position) и счетчик шагов (steps).

Используйте цикл, чтобы добавлять к position текущее количество шагов и увеличивать steps.

Если position достигает или превышает target и разница между position и target четная, остановите цикл и return steps.

😎

Vacancies for this task

활성 채용 with overlapping task tags are 표시됨.

전체 채용
아직 활성 채용이 없습니다.