LeetCode 69: Sqrt(x)

題目鏈接:

https://leetcode.com/problems/sqrtx/description/

描述

Implement int sqrt(int x).

Compute and return the square root of x.

輸入

輸入一個自然數

輸出

輸出該自然數的平方根(最接近的)

樣例輸入

16
18

樣例輸出

4
4

算法思想:

這道題使用到了本科學過的數值分析,可以使用牛頓迭代法,非常經典。跟泰勒公式很像。
牛頓迭代法簡介下:
[牛頓迭代法簡介:http://blog.csdn.net/young_gy/article/details/45766433]

源代碼

class Solution {
public:
    int sqr(double x)  
    {  
        double k=x;  
        while(k*k-x>1e-6)  
            k=0.5*(k+x/k);  
        return k;  
    }  
    int mySqrt(int x) {
        int ans = sqr(x);
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章