当前位置:网站首页>leetcode 072. Finding Square Roots
leetcode 072. Finding Square Roots
2022-08-03 20:11:00 【Luna who can program】
给定一个非负整数 x ,计算并返回 x 的平方根,即实现 int sqrt(int x) 函数.
正数的平方根有两个,只输出其中的正数平方根.
如果平方根不是整数,输出只保留整数的部分,小数部分将被舍去.
示例 1:
输入: x = 4
输出: 2
示例 2:
输入: x = 8
输出: 2
解释: 8 的平方根是 2.82842…,由于小数部分将被舍去,所以返回 2
提示:
0 <= x <= 231-1
思路:二分
c++
class Solution {
public:
int mySqrt(int x) {
long long left=0,right=x,ans,mid;
while(left<=right){
mid=left+(right-left)/2; //和 mid=(right+left)/2 等价,但是 left+right 可能会溢出
if((long long)mid*mid<=x){
//mid*mid 也可能会溢出,所以用 long long
ans=mid;
left=mid+1;
}
else
right=mid-1;
}
return ans;
}
};
python
class Solution:
def mySqrt(self, x: int) -> int:
left,right,ans=0,x,0
while left<=right:
mid=(left+right)//2
if mid**2<=x:
ans=mid
left=mid+1
else:
right=mid-1
return ans
牛顿迭代:
c++:
class Solution {
public:
int mySqrt(int x) {
if(x==0) //Avoid the following denominator as0的情况
return 0;
double x0=x,c=x,xi;
while(1){
xi=(x0+c/x0)/2;
if(fabs(x0-xi)<1e-7)
break;
x0=xi;
}
return x0;
}
};
python:
class Solution:
def mySqrt(self, x: int) -> int:
if x==0:
return 0
x0,c=float(x),float(x)
while 1:
xi=(x0+c/x0)/2
if abs(xi-x0)<1e-7:
break
x0=xi
return int(x0)
The formula of Newton's iteration needs to understand its principle,You can refer to this article for a very detailed explanation(写的很详细):
边栏推荐
猜你喜欢
钱江摩托某型号产品ECU货不对版 消费者知情权应如何保障?
揭秘5名运维如何轻松管理数亿级流量系统
Internet Download Manager简介及下载安装包,IDM序列号注册问题解决方法
亚马逊云科技 Build On 2022 - AIot 第二季物联网专场实验心得
使用 ReportLab 绘制 PDF
NNLM、RNNLM等语言模型 实现 下一单词预测(next-word prediction)
边缘盒子+时序数据库,美的数字化平台 iBuilding 背后的技术选型
leetcode 231. 2 的幂
1161 最大层内元素和——Leetcode天天刷【BFS】(2022.7.31)
(十六)51单片机——红外遥控
随机推荐
Statistical machine learning 】 【 linear regression model
数学之美 第六章——信息的度量和作用
Edge box + time series database, technology selection behind Midea's digital platform iBuilding
async 和 await 原来这么简单
CLIP论文解读
谁的孙子最多II
Detailed steps for tensorflow-gpu2.4.1 installation and configuration
【飞控开发高级教程4】疯壳·开源编队无人机-360 度翻滚
YARN功能介绍、交互流程及调度策略
MySQL Basics
2022.8.2
RNA核糖核酸修饰Alexa 568/[email protected] 594/[email prote
调用EasyCVR接口时视频流请求出现404,并报错SSL Error,是什么原因?
【leetcode】剑指 Offer II 008. 和大于等于 target 的最短子数组(滑动窗口,双指针)
ES6简介及let、var、const区别
【leetcode】剑指 Offer II 007. 数组中和为 0 的三个数(双指针)
The sword refers to Offer II 044. The maximum value of each level of the binary tree-dfs method
pytorch框架实现老照片修复功能详细演示(GPU版)
多模态 参考资料汇总
tensorflow-gpu2.4.1安装配置详细步骤