[LeetCode] Sqrt(x)

1.Implement int sqrt(int x).
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.

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.

2.题目要求:求平方根。

3.方法:算一个候选值的平方,然后和x比较大小。采用牛顿迭代法,因为要求x的平方 = n的解,令f(x)=x的平方-n,相当于求解f(x)=0的解,可以求出递推式。

4.代码:
class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0;
double res = 1, pre = 0;
while (res != pre) {
pre = res;
res = (res + x / res) / 2;
}
return int(res);
}
};

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,793评论 0 33
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,040评论 0 38
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,288评论 19 139
  • 第90天 姓名:董蕴英 公司:沈阳建筑装饰装修有限公司 【知~学习】 《六项精进》大纲1遍 共209遍 《大学》开...
    董生活阅读 89评论 0 0
  • 哈喽
    简书2468阅读 246评论 0 0