LeetCode-69:Sqrt(x) (整數的平方根)

題目:

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 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2

Explanation: The square root of 8 is 2.82842…, and since
the decimal part is truncated, 2 is returned.

問題解析:

求給定整數x的平方根。

鏈接:

思路標籤:

算法:二分法

解答:

1. 二分法

  • 使用二分法在1~x的範圍內進行查找;
  • 雖然題目簡單,但是需要注意的邊界範圍,以及mid的賦值方式需要考慮;
class Solution {
public:
    int mySqrt(int x) {
        if (0 == x) return 0;
        int left = 1, right = x, ans;
        while (left <= right) {
            int mid = left + (right - left) / 2; //mid爲在原來的基礎上+一半
            if (mid <= x / mid) {
                left = mid + 1;
                ans = mid;
            } else {
                right = mid - 1;
            }
        }
        return ans;
    }
};

2. 牛頓法

  • 直接利用牛頓法求解。
  • 具體解釋自行Google。
class Solution {
public:
    int mySqrt(int x) {
        long r = x;
        while (r*r > x)
            r = (r + x/r) / 2;
        return r;
    }
};
發佈了200 篇原創文章 · 獲贊 740 · 訪問量 69萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章