LeetCode question number: 69. Square root of x
Calculate and return the square root of x, where x is a non-negative integer. Since the return type is an integer, only the integer part of the result is retained, and the decimal part will be discarded.
Example 1:
Input: 4
Output: 2
Example 2:Input: 8
Output: 2
Description: The square root of 8 is 2.82842..., since the return type is an integer, the fractional part will be discarded.
1. Brute force cracking, traversal to find value.
2. Dichotomy.
Induction: Since the integer part of the square root of x must satisfy the maximum k value of k^2≤x. Just start from this point
//暴力破解
func mySqrt(x int) int {
var num int = 0
for num*num <= x {
if (num+1)*(num+1) > x {
return num
}
num++
}
return num
}
func mySqrt1(x int) int {
left, right := 0, x
ans := -1
for left < right {
mid := left + (right-left)/2
if mid*mid <= x {
ans = mid
left = mid + 1
} else {
right = mid - 1
}
}
return ans
}
Past review:
[1] LeetCode-876. The middle node of the linked list (implemented by Goland)
[3] LeetCode-21. Merging two ordered linked lists (implemented by Goland)
❤If the article is helpful to you, please click like at the top right corner of the article or at the end of the article! (づ ̄ 3 ̄)づ
❤If you like the articles shared by the white rabbit, please pay attention to the white rabbit! (๑′ᴗ‵๑)づ╭❤~
❤If you have any questions about the article, please leave a message below or join the group to discuss [group number: 708072830]
❤In view of the limited personal experience, all opinions and technical research points, if you have any objections, please reply directly to the discussion (do not make offensive remarks)