[Leetcode] 69. Sqrt(x)

更新於 發佈於 閱讀時間約 2 分鐘

題目 : 69. Sqrt(x)

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

Example 1:

Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.


1.

x = 8

解題思路

解題思路


依照題目所說的取最接近小於等於該開根號後所得出的整數部分,所以答案是i

class Solution:
def mySqrt(self, x: int) -> int:

# 先將例外的例子,如0和1先行做判斷
# 0和1的根號分別都是0和1,所以可以直接回傳本身的數字
if x == 0 or x == 1:
return x

# 思路如上圖所示
for i in range(x):
if i*i <= x and x < (i+1)*(i+1) :
return i


留言
avatar-img
留言分享你的想法!
avatar-img
Youna's Devlog
7會員
49內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
Youna's Devlog的其他內容
2024/02/13
題目 : 121. Best Time to Buy and Sell Stock
Thumbnail
2024/02/13
題目 : 121. Best Time to Buy and Sell Stock
Thumbnail
2024/01/11
題目 : 100. Same Tree
Thumbnail
2024/01/11
題目 : 100. Same Tree
Thumbnail
2024/01/11
題目 : 83. Remove Duplicates from Sorted List
Thumbnail
2024/01/11
題目 : 83. Remove Duplicates from Sorted List
Thumbnail
看更多
你可能也想看
Thumbnail
Leetcode 精選75題 題目與題解 熱門考點 目錄 (持續更新中) 建議從左側目錄 或者 按Ctrl+F輸入關鍵字進行搜尋
Thumbnail
Leetcode 精選75題 題目與題解 熱門考點 目錄 (持續更新中) 建議從左側目錄 或者 按Ctrl+F輸入關鍵字進行搜尋
Thumbnail
題目敘述 給定一個非零陣列nums,請找出陣列裡面 最大的對偶數 是誰? 如果無解,請返回-1 對偶數定義: 整數k的對偶數是-k 例如: 99 和 -99互為對偶數。
Thumbnail
題目敘述 給定一個非零陣列nums,請找出陣列裡面 最大的對偶數 是誰? 如果無解,請返回-1 對偶數定義: 整數k的對偶數是-k 例如: 99 和 -99互為對偶數。
Thumbnail
題目敘述 題目會給定一個猜數字的場景和介面 (包含一個可以呼叫,驗證是否為答案的API guess() function), 要求我們實現猜數字的function guessNumber(int n)。 題目已經事先設定好一個祕密數字,要求我們去找出來那個祕密數字是多少。 就好像小時候
Thumbnail
題目敘述 題目會給定一個猜數字的場景和介面 (包含一個可以呼叫,驗證是否為答案的API guess() function), 要求我們實現猜數字的function guessNumber(int n)。 題目已經事先設定好一個祕密數字,要求我們去找出來那個祕密數字是多少。 就好像小時候
Thumbnail
題目 : 27. Remove Element
Thumbnail
題目 : 27. Remove Element
Thumbnail
題目 : 88. Merge Sorted Array
Thumbnail
題目 : 88. Merge Sorted Array
Thumbnail
題目 : 69. Sqrt(x)
Thumbnail
題目 : 69. Sqrt(x)
Thumbnail
題目 : 35. Search Insert Position
Thumbnail
題目 : 35. Search Insert Position
追蹤感興趣的內容從 Google News 追蹤更多 vocus 的最新精選內容追蹤 Google News