69. Sqrt(x)

LeetCode easy original: C# #csharp #easy #leetcode #math #two-pointers
El texto de la tarea se traduce del ruso para el idioma seleccionado. El código no cambia.

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

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

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

Ejemplo:

Input: x = 4

Output: 2

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

C# solución

coincidente/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++ solución

borrador automático, revisar antes de enviar
#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 solución

coincidente/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 solución

coincidente/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 solución

coincidente/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 solución

coincidente/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, entero квадратный корень найден, давайте вернем его.

3️⃣

return right.

😎

Vacantes para esta tarea

Se muestran vacantes activas con etiquetas coincidentes.

Todas las vacantes
Todavía no hay vacantes activas.