69. Sqrt(x)

LeetCode easy original: C# #csharp #easy #leetcode #math #two-pointers
Der Aufgabentext wird für die gewählte Sprache aus dem Russischen übersetzt. Code bleibt unverändert.

given неотрицательное Ganzzahl x. return квадратный корень из x, округлённый вниз до ближайшего целого числа. Возвращаемое Ganzzahl также должно быть неотрицательным.

Вы не должны использовать встроенные функции или операторы для возведения в степень.

НаBeispiel, не следует использовать pow(x, 0.5) в C++ или x ** 0.5 в Python.

Beispiel:

Input: x = 4

Output: 2

Explanation: The square root of 4 is 2, so we return 2.

C# Lösung

zugeordnet/original
public class Solution {
    public int MySqrt(int x) {
        if (x < 2)
            return x;
        long num;
        int pivot, left = 2, right = x / 2;
        while (left <= right) {
            pivot = left + (right - left) / 2;
            num = (long)pivot * pivot;
            if (num > x)
                right = pivot - 1;
            else if (num < x)
                left = pivot + 1;
            else
                return pivot;
        }
        return right;
    }
}

C++ Lösung

Auto-Entwurf, vor dem Einreichen prüfen
#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 MySqrt(int x) {
        if (x < 2)
            return x;
        long num;
        int pivot, left = 2, right = x / 2;
        while (left <= right) {
            pivot = left + (right - left) / 2;
            num = (long)pivot * pivot;
            if (num > x)
                right = pivot - 1;
            else if (num < x)
                left = pivot + 1;
            else
                return pivot;
        }
        return right;
    }
}

Java Lösung

zugeordnet/original
class Solution {
    public int mySqrt(int x) {
        if (x < 2) return x;

        long num;
        int pivot, left = 2, right = x / 2;
        while (left <= right) {
            pivot = left + (right - left) / 2;
            num = (long) pivot * pivot;
            if (num > x) right = pivot - 1;
            else if (num < x) left = pivot + 1;
            else return pivot;
        }

        return right;
    }
}

JavaScript Lösung

zugeordnet/original
var mySqrt = function (x) {
    if (x < 2) return x;
    let num;
    let pivot,
        left = 2,
        right = Math.floor(x / 2);
    while (left <= right) {
        pivot = left + Math.floor((right - left) / 2);
        num = pivot * pivot;
        if (num > x) right = pivot - 1;
        else if (num < x) left = pivot + 1;
        else return pivot;
    }
    return right;
};

Python Lösung

zugeordnet/original
class Solution:
    def mySqrt(self, x: int) -> int:
        if x < 2:
            return x

        left, right = 2, x // 2

        while left <= right:
            pivot = left + (right - left) // 2
            num = pivot * pivot
            if num > x:
                right = pivot - 1
            elif num < x:
                left = pivot + 1
            else:
                return pivot

        return right

Go Lösung

zugeordnet/original
func mySqrt(x int) int {
    if x < 2 {
        return x
    }
    var num int
    pivot, left, right := 2, 2, x/2
    for left <= right {
        pivot = left + (right-left)/2
        num = pivot * pivot
        if num > x {
            right = pivot - 1
        } else if num < x {
            left = pivot + 1
        } else {
            return pivot
        }
    }
    return right
}

Algorithm

1️⃣

Если x < 2, return x. Установите левую границу left = 2 и правую границу right = x / 2.

2️⃣

Пока left ≤ right:

Возьмите num = (left + right) / 2 в качестве предположения. Вычислите num × num и сравните его с x:

Если num × num > x, переместите правую границу right = pivot − 1.

В противном случае, если num × num < x, переместите левую границу left = pivot + 1.

В противном случае num × num == x, Ganzzahl квадратный корень найден, давайте вернем его.

3️⃣

return right.

😎

Stellen zu dieser Aufgabe

aktive Stellen with overlapping task tags are angezeigt.

Alle Stellen
Es gibt noch keine aktiven Stellen.