题目描述:

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

本题让我们写一个类似sqrt()的函数,不过返回值和输入值都改成了int类型。

例子:

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

解题思路:

这道题我一开始是用遍历的方法,结果数据溢出了。然后我看了别人的方法才发现我的代码实在是low,别人都用的牛顿迭代法,最起码也是二分法。然后我又重新写了个用牛顿迭代法做的代码。

牛顿迭代法:

y(t)=t²-x

切线方程为:y(t)=2t₁(t-t₁)+t₁²-x

整理得到t=x/2t₁+t₁/2

代码:

 1 class Solution {
 2 public:
 3     int mySqrt(int x) {
 4         double result=1;
 5         while(abs(result*result-x)>0.000001){
 6             result=x/(2*result)+result/2;
 7         }
 8         return (int)result;
 9     }
10 };

 

posted on 2018-02-05 10:26  宵夜在哪  阅读(94)  评论(0编辑  收藏  举报