题目描述:

实现 int sqrt(int x) 函数,计算并返回 x 的平方根。

样例

sqrt(3) = 1

sqrt(4) = 2

sqrt(5) = 2

sqrt(10) = 3

题解:

解法1:

/// 解法1: O(sqrt(n))
class Solution {
public:
/**
* @param x: An integer
* @return: The sqrt of x
*/
int sqrt(int x) {
// write your code here
for (int i=0; i*i<=x; ++i) {
long long temp = (long long)(i+1)*(i+1);
if (temp > x) {
return i;
}
}
}
};

解法2:

二分

///解法2: O(log(n))

class Solution {
public:
/**
* @param x: An integer
* @return: The sqrt of x
*/
int sqrt(int x) {
// write your code her
int l = 1;
int r = x / 2 + 1; // ans >= 1 && ans <= x/2 + 1
while(l <= r) {
long long mid = (l + r) / 2;
long long t1 = mid * mid;
long long t2 = (mid + 1) * (mid + 1);
if (t1 == x || (t1 < x && t2 > x)) return mid;
if (t1 < x) {
l = mid + 1;
}else r = mid - 1;
}
}
};

解法3:

牛顿迭代法

///解法3: 牛顿迭代法
/* f(x) = n - x * x
* Xi+1 = Xi - f(Xi)/f'(Xi)
* Xi+1 = Xi - (n - Xi*Xi)/(-2*Xi)
* Xi+1 = (Xi + n / Xi) / 2
*/ class Solution {
public:
/**
* @param x: An integer
* @return: The sqrt of x
*/
int sqrt(int x) {
write your code her
if (x == 0) return 0;
double l = 0;
double r = 1;
while(l != r) {
double t = r;
l = (r + x*1.0 / r) / 2.0;
r = l;
l = t;
}
return (int) l;
}
};

参考链接:

https://zh.wikipedia.org/wiki/%E7%89%9B%E9%A1%BF%E6%B3%95

http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html

最新文章

  1. Android: R cannot be resolved to a varia...
  2. 从零开始学iPhone开发(4)——使用WebView
  3. HDU 4717 The Moving Points (三分法)
  4. javascript 漏洞
  5. 2模02day1题解
  6. ThinkPHP 模板截取字符串 【转载】
  7. 通知---iOS
  8. Xcode中 xx duplicate symbols for architecture i386错误提示
  9. openMPI小集群安装
  10. 要将程序集“xxx.dll”标记为系统必备组件,必须对其进行强签名
  11. unity 3d 生成apk文件时,设置图标
  12. 查看Oracle数据库某用户的连接信息
  13. 一天一个类,一点也不累 之 Vector
  14. Java中的抽象
  15. mycat 主从切换分析过程
  16. angularjs学习第七天笔记(系统指令学习)
  17. 【Tomcat】tomcat配置文件详解
  18. OpenCV教程(48) 特征值匹配
  19. JERSEY中文翻译(第三章、模块和依赖)
  20. ubuntu 系统网络突然&quot;网络已禁用&quot;

热门文章

  1. [原][osg][osgEarth]EarthManipulator关于oe漫游器的handle部分解读以及修改(仿照谷歌,修改oe漫游器中focal(视角切换)功能 续 二)
  2. $(document).ready和window.onload,细微小区别,ready是jQuery的方法,onload是window的方法
  3. 学习笔记23—window10 64位 python2.7 安装liblinear
  4. redux与redux-react使用示例
  5. repeater绑定dropdownlist,jquery+ajax页面无刷新,修改dropdownlist默认值
  6. (转)C# Delegate.Invoke、Delegate.BeginInvoke
  7. Getting Started with Processing 第五章的总结
  8. Bulk RNA-Seq转录组学习
  9. English trip V1 - 10.Family Ties 家庭关系 Teacher:Emily Key: Possessive s (所有格 s)
  10. 20171205xlVBA往返航班组合