当前位置:网站首页>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(写的很详细):
边栏推荐
猜你喜欢

高位套牢机构,用友网络的信任危机是如何产生的?

Line the last time the JVM FullGC make didn't sleep all night, collapse

高效目标检测:动态候选较大程度提升检测精度(附论文下载)

ECCV 2022 Oral | 满分论文!视频实例分割新SOTA: IDOL

数据驱动的软件智能化开发| ChinaOSC

【leetcode】剑指 Offer II 008. 和大于等于 target 的最短子数组(滑动窗口,双指针)

收藏-即时通讯(IM)开源项目OpenIM-功能手册

不知道这4种缓存模式,敢说懂缓存吗?

头条服务端一面经典10道面试题解析

ThreadLocal详解
随机推荐
ES6解构赋值--数组解构及对象解构
头条服务端一面经典10道面试题解析
leetcode 231. 2 的幂
Pytorch GPU 训练环境搭建
深入理解JVM-内存结构
Matlab paper illustration drawing template No. 42 - bubble matrix diagram (correlation coefficient matrix diagram)
力扣203-移除链表元素——链表
算法--交错字符串(Kotlin)
MapReduce介绍及执行过程
按需视觉识别:愿景和初步方案
LeetCode 1374. 生成每种字符都是奇数个的字符串
开源教育论坛| ChinaOSC
ES6-箭头函数
C中的数据存储
Anaconda virtual environment migration
倒计时2天,“文化数字化战略新型基础设施暨文化艺术链生态建设发布会”启幕在即
php截取中文字符串实例
刷题错题录1-隐式转换与精度丢失
Detailed demonstration pytorch framework implementations old photo repair (GPU)
Go语言为任意类型添加方法