当前位置:网站首页>69. x的平方根
69. x的平方根
2022-06-11 21:36:00 【爱学代码的学生】
题目描述:
给你一个非负整数 x ,计算并返回 x 的算术平方根 。
由于返回类型是整数,结果只保留整数部分 ,小数部分将被舍去 。
注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。
题目分析:
对于此题我们要明白一个数学规律:一个正数x的平方根是>= x / 2,有了这个规律我们可以想到二分法来选择做此题。
1. 二分法
int mySqrt(int x){
int left=1;
int right=x/2+1; //这里本身是可以为x/2但因为有0这个因素的考虑,因此right+1
while(left<=right){
int mid = left+((right-left)>>1);//这里等价于 mid = (right+left)/2 ,这里这样写是避免溢出
if(mid>x/mid){
right=mid-1;
}
else if(mid<x/mid){
left=mid+1;
}
else{
return mid; //条件满足则返回
}
}
return right; //最后要返回的是零向取整的值,因此返回right
}2. 牛顿迭代法
思路
牛顿迭代法是一种可以用来快速求解函数零点的方法。
f(y) = y^2 - C
将C换成 引入值,则y就是所求值.
代码如下:
int mySqrt(int x){
if(x==0){ //特殊情况
return 0;
}
double c=x;
double x0=x;
while(1){
double x1 = (x0+c/x0)*0.5;
if(fabs(x0-x1)<1e-7){ //满足两者距离小于e*10^-7次方退出
break;
}
x0=x1;
}
return (int)x0; //返回取整值
}边栏推荐
- LeetCode-322-零钱兑换
- LeetCode-104-二叉树的最大深度
- 多态的所有特征
- 每日一题 -- 验证回文串
- 2021 Niuke multi school 5 double strings
- Educational Codeforces Round 114 (Rated for Div. 2) D
- 使用 SAP UI5 CLI 命令行工具构建和运行 SAP UI5 应用
- How to import workflows provided on SAP API hub to sap BTP
- 实验10 Bezier曲线生成-实验提高-控制点生成B样条曲线
- BZOJ3189 : [Coci2011] Slika
猜你喜欢

Database daily question --- day 9: salesperson

The upcoming launch of the industry's first retail digital innovation white paper unlocks the secret of full link digital success

Leetcode-129- sum of numbers from root node to leaf node
![BZOJ3189 : [Coci2011] Slika](/img/46/c3aa54b7b3e7dfba75a7413dfd5b68.png)
BZOJ3189 : [Coci2011] Slika

华为设备配置H-VPN

Flink error: multiple tasks are started, and only one task is executed

Leetcode-110-balanced binary tree

C语言实现迷宫问题
![[Part 14] source code analysis and application details of completionservice class [key]](/img/41/9f5383d6eafb32723e29c15da3a1af.jpg)
[Part 14] source code analysis and application details of completionservice class [key]

Customer information management software
随机推荐
Apache local multi port configuration
flutter系列之:flutter中常用的container layout详解
Diary at 16:29:41 on June 9, 2022
如何利用RPA机器人开启货代行业数字化转型第一步?
RPA超自动化 | 农耕记携手云扩加速财务智能化运营
[Part 16] copyonwritearraylist source code analysis and application details [key]
Customer information management software
Codeforces Round #739 (Div. 3)解题报告
如何使用 SAP Kyma 控制台手动发送 SAP Commerce Cloud Mock 应用暴露的事件
Game client performance (memory) [previous]
bzoj3188 Upit
Educational Codeforces Round 114 (Rated for Div. 2) D
Deploy SAP ui5 applications to the sap BTP kyma operating environment step by step
每日一题 -- 验证回文串
JVM | runtime data area; Program counter (PC register);
Relatively perfect singleton mode
Add anti debugging function to game or code (application level)
Refresh and upgrade | innovation, starting from cloud store
Using the sap ui5 cli command line tool to build and run SAP ui5 applications
Introduction à endnotex9 et instructions pour les tutoriels de base