69. Sqrt(x)
https://leetcode.com/problems/sqrtx/
Easy
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.
Example 1:
Input: x = 4 Output: 2
Example 2:
Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
Constraints:
0 <= x <= 231 - 1
題意
對 x 開根號後的整數為為多少?
解題思路
我們來使用二分搜尋法,讓左右邊界快速縮減,透過 mid 的次方,就可以知道 x 的根號會落在哪邊了,今天程式碼比較簡短,所以就不寫步驟了。
原始碼
func mySqrt(x int) int {
left := 1
right := x
for left < right {
mid := (left + right + 1) / 2
if mid * mid > x {
right = mid - 1
} else {
left = mid
}
}
return right
}
結尾
你有更好或更簡單的解決方案嗎?
歡迎到我的 Facebook Alan 的筆記本 留言,順手給我個讚吧!你的讚將成為我持續更新的動力,感謝你的閱讀,讓我們一起學習成為更好的自己。