iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 29
0
自我挑戰組

Leetcode新手挑戰30天系列 第 29

#69 Sqrt(x)

寫在開頭

今天選的一樣是#Easy的題目

進入正題

題目如下:

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.

這題我想得到的做法比較簡單,因為輸入的數字預期是一個數的平方,輸出是要找到這個數的平方根,正好python有個算平方的公式,可以計算0.5平方,就可以得到平方根。
所以我的程式碼如下:

def mySqrt(self, x: int) -> int:
    return int(pow(x, 0.5) // 1)

跑了範例1和2作為測試後沒問題,submit的結果如下:
https://ithelp.ithome.com.tw/upload/images/20190930/20113393qsvtkQvl9D.png

參考資料


上一篇
#1185 Day of the Week
下一篇
#204 Count Primes
系列文
Leetcode新手挑戰30天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言