Sqrt(x)
https://leetcode.com/problems/sqrtx/description/
Implement
int sqrt(int x)
.Compute and return the square root ofx.
x is guaranteed to be a non-negative integer.
Thoughts
这道题可以用二分法做, 即每次取[1, x/2]中值 (x/2因为只要sqrt大于2就一定会比x/2小), 判断mid ^ 2是大于还是小于等于x。 注意最开始的几个值可能溢出, 因此初始end 取46340即可。
还有可以用牛顿迭代法做. 每次取切线与0的交点r, 看r ^ 2 是否>x, 是则继续, 否则返回.
https://zh.wikipedia.org/wiki/%E7%89%9B%E9%A1%BF%E6%B3%95
https://www.zhihu.com/question/20690553
Code
Analysis
未知.
Last updated
Was this helpful?