C++實現(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.
這道題要求我們求平方根,我們能想到的方法就是算一個候選值的平方,然后和x比較大小,為了縮短查找時間,我們采用二分搜索法來找平方根,找最后一個不大于目標(biāo)值的數(shù),這里細(xì)心的童鞋可能會有疑問,在總結(jié)貼中第三類博主的 right 用的是開區(qū)間,那么這里為啥 right 初始化為x,而不是 x+1 呢?因為總結(jié)帖里的 left 和 right 都是數(shù)組下標(biāo),這里的 left 和 right 直接就是數(shù)字本身了,一個數(shù)字的平方根是不可能比起本身還大的,所以不用加1,還有就是這里若x是整型最大值,再加1就會溢出。最后就是返回值是 right-1,因為題目中說了要把小數(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ù)中好像講到過這個方法,是用逼近法求方程根的神器,在這里也可以借用一下,因為要求 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); } };
也是牛頓迭代法,寫法更加簡潔一些,注意為了防止越界,聲明為長整型,參見代碼如下:
解法三:
class Solution { public: int mySqrt(int x) { long res = x; while (res * res > x) { res = (res + x / res) / 2; } return res; } };
到此這篇關(guān)于C++實現(xiàn)LeetCode( 69.求平方根)的文章就介紹到這了,更多相關(guān)C++實現(xiàn)求平方根內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++基于EasyX框架實現(xiàn)飛機(jī)大戰(zhàn)小游戲
EasyX是針對C/C++的圖形庫,可以幫助使用C/C++語言的程序員快速上手圖形和游戲編程。本文將利用EasyX框架實現(xiàn)飛機(jī)大戰(zhàn)小游戲,需要的可以參考一下2023-01-01Linux下semop等待信號時出現(xiàn)Interrupted System Call錯誤(EINTR)解決方法
本篇文章是對在Linux下semop等待信號時出現(xiàn)Interrupted System Call錯誤(EINTR)的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05