Skip to content

Latest commit

 

History

History
54 lines (46 loc) · 1.02 KB

069.Sqrtx.md

File metadata and controls

54 lines (46 loc) · 1.02 KB

69.Sqrt(x)

Question:

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example:

Input: 4
Output: 2

Solution:

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        r = x
        while r*r > x:
            r = (r + x / r) / 2
        return r

Solution:

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

本题关键:

  • 这是一个二分法的题目