C++實(shí)現(xiàn)LeetCode( 69.求平方根)
[LeetCode] 69. Sqrt(x) 求平方根
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
這道題要求我們求平方根,我們能想到的方法就是算一個(gè)候選值的平方,然后和x比較大小,為了縮短查找時(shí)間,我們采用二分搜索法來(lái)找平方根,找最后一個(gè)不大于目標(biāo)值的數(shù),這里細(xì)心的童鞋可能會(huì)有疑問(wèn),在總結(jié)貼中第三類博主的 right 用的是開(kāi)區(qū)間,那么這里為啥 right 初始化為x,而不是 x+1 呢?因?yàn)榭偨Y(jié)帖里的 left 和 right 都是數(shù)組下標(biāo),這里的 left 和 right 直接就是數(shù)字本身了,一個(gè)數(shù)字的平方根是不可能比起本身還大的,所以不用加1,還有就是這里若x是整型最大值,再加1就會(huì)溢出。最后就是返回值是 right-1,因?yàn)轭}目中說(shuō)了要把小數(shù)部分減去,只有減1才能得到正確的值,代碼如下:
解法一:
class Solution {
public:
int mySqrt(int x) {
if (x <= 1) return x;
int left = 0, right = x;
while (left < right) {
int mid = left + (right - left) / 2;
if (x / mid >= mid) left = mid + 1;
else right = mid;
}
return right - 1;
}
};
這道題還有另一種解法,是利用牛頓迭代法,記得高數(shù)中好像講到過(guò)這個(gè)方法,是用逼近法求方程根的神器,在這里也可以借用一下,因?yàn)橐?x2 = n 的解,令 f(x)=x2-n,相當(dāng)于求解 f(x)=0 的解,可以求出遞推式如下:
xi+1=xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2
解法二:
class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0;
double res = 1, pre = 0;
while (abs(res - pre) > 1e-6) {
pre = res;
res = (res + x / res) / 2;
}
return int(res);
}
};
也是牛頓迭代法,寫(xiě)法更加簡(jiǎn)潔一些,注意為了防止越界,聲明為長(zhǎng)整型,參見(jiàn)代碼如下:
解法三:
class Solution {
public:
int mySqrt(int x) {
long res = x;
while (res * res > x) {
res = (res + x / res) / 2;
}
return res;
}
};
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode( 69.求平方根)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)求平方根內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C++實(shí)現(xiàn)LeetCode(73.矩陣賦零)
- C++實(shí)現(xiàn)LeetCode(72.編輯距離)
- C++實(shí)現(xiàn)LeetCode(71.簡(jiǎn)化路徑)
- C++實(shí)現(xiàn)LeetCode(68.文本左右對(duì)齊)
- C++實(shí)現(xiàn)LeetCode(67.二進(jìn)制數(shù)相加)
- C++實(shí)現(xiàn)LeetCode(66.加一運(yùn)算)
- C++實(shí)現(xiàn)LeetCode(174.地牢游戲)
- C++實(shí)現(xiàn)LeetCode(81.在旋轉(zhuǎn)有序數(shù)組中搜索之二)
相關(guān)文章
C++基于EasyX框架實(shí)現(xiàn)飛機(jī)大戰(zhàn)小游戲
EasyX是針對(duì)C/C++的圖形庫(kù),可以幫助使用C/C++語(yǔ)言的程序員快速上手圖形和游戲編程。本文將利用EasyX框架實(shí)現(xiàn)飛機(jī)大戰(zhàn)小游戲,需要的可以參考一下2023-01-01
C++無(wú)法打開(kāi)源文件bits/stdc++.h的問(wèn)題
這篇文章主要介紹了C++無(wú)法打開(kāi)源文件bits/stdc++.h的問(wèn)題以及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
Linux下semop等待信號(hào)時(shí)出現(xiàn)Interrupted System Call錯(cuò)誤(EINTR)解決方法
本篇文章是對(duì)在Linux下semop等待信號(hào)時(shí)出現(xiàn)Interrupted System Call錯(cuò)誤(EINTR)的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C語(yǔ)言如何建立動(dòng)態(tài)鏈表問(wèn)題
這篇文章主要介紹了C語(yǔ)言如何建立動(dòng)態(tài)鏈表問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12

