leetcode 69 Sqrt(x)

python:

class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        left = 0
        right = x
        while (left <= right):
            mid = (left + right)//2
            if mid**2 <= x:
                left = mid + 1
            else :
                right = mid - 1
        return left - 1

c++:

class Solution {
public:
    int mySqrt(int x) {
        long long left = 0, right = x;
        while(left <= right){
            long long mid = (left + right)/2;
            if (mid * mid <= x)
                left = mid + 1;
            else
                right = mid - 1;
        }
        return left - 1;
    }
};

猜你喜欢

转载自blog.csdn.net/MRxjh/article/details/82348306