【LeetCode】69. Sqrt(x) (2 solutions)
生活随笔
收集整理的這篇文章主要介紹了
【LeetCode】69. Sqrt(x) (2 solutions)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Sqrt(x)
Implement?int sqrt(int x).
Compute and return the square root of?x.
?
解法一:牛頓迭代法
求n的平方根,即求f(x)=x2-n的零點(diǎn)
設(shè)初始值為x0,注,不要設(shè)為0,以免出現(xiàn)除數(shù)為0,見(jiàn)后。
則過(guò)(x0,f(x0))點(diǎn)的切線為g(x)=f(x0)+f'(x0)*(x-x0)
g(x)與x軸的交點(diǎn)為x1=x0-f(x0)/f'(x0)
遞推關(guān)系為xn+1=xn-f(xn)/f'(xn)
當(dāng)收斂時(shí)即為解。
class Solution { public:int sqrt(int x) {double x0 = 1;double x_next = -(x0*x0 - x)/(2*x0) + x0;while(fabs(x0-x_next) > 0.00001){x0 = x_next;x_next = -(x0*x0 - x)/(2*x0) + x0;}return x0;} };?
解法二:二分法
注意返回為int,結(jié)果會(huì)取整。
class Solution { public:int sqrt(int x) {long long low = 0;long long high = x;long long mid;while(low <= high){mid = (low+high)/2;long long result = mid*mid;if(result == x)return mid;else if(result > x)high = mid-1;elselow = mid+1;}return high;} };轉(zhuǎn)載于:https://www.cnblogs.com/ganganloveu/p/4153935.html
總結(jié)
以上是生活随笔為你收集整理的【LeetCode】69. Sqrt(x) (2 solutions)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: WebForms Unobtrusive
- 下一篇: NewSQL数据库VoltDB特性简介