X的平方
2024-08-26 20:58:16
题目描述:
实现 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
最新文章
- Android: R cannot be resolved to a varia...
- 从零开始学iPhone开发(4)——使用WebView
- HDU 4717 The Moving Points (三分法)
- javascript 漏洞
- 2模02day1题解
- ThinkPHP 模板截取字符串 【转载】
- 通知---iOS
- Xcode中 xx duplicate symbols for architecture i386错误提示
- openMPI小集群安装
- 要将程序集“xxx.dll”标记为系统必备组件,必须对其进行强签名
- unity 3d 生成apk文件时,设置图标
- 查看Oracle数据库某用户的连接信息
- 一天一个类,一点也不累 之 Vector
- Java中的抽象
- mycat 主从切换分析过程
- angularjs学习第七天笔记(系统指令学习)
- 【Tomcat】tomcat配置文件详解
- OpenCV教程(48) 特征值匹配
- JERSEY中文翻译(第三章、模块和依赖)
- ubuntu 系统网络突然";网络已禁用";
热门文章
- [原][osg][osgEarth]EarthManipulator关于oe漫游器的handle部分解读以及修改(仿照谷歌,修改oe漫游器中focal(视角切换)功能 续 二)
- $(document).ready和window.onload,细微小区别,ready是jQuery的方法,onload是window的方法
- 学习笔记23—window10 64位 python2.7 安装liblinear
- redux与redux-react使用示例
- repeater绑定dropdownlist,jquery+ajax页面无刷新,修改dropdownlist默认值
- (转)C# Delegate.Invoke、Delegate.BeginInvoke
- Getting Started with Processing 第五章的总结
- Bulk RNA-Seq转录组学习
- English trip V1 - 10.Family Ties 家庭关系 Teacher:Emily Key: Possessive s (所有格 s)
- 20171205xlVBA往返航班组合