爲了增加自己對go的熱愛,畢竟go的Logo辣麼可愛,我決定刷一組新題目,easy還是很容易滴
題目
實現 int sqrt(int x) 函數。
計算並返回 x 的平方根,其中 x 是非負整數。
由於返回類型是整數,結果只保留整數的部分,小數部分將被捨去。
示例 1:
輸入: 4
輸出: 2
示例 2:
輸入: 8
輸出: 2
說明: 8 的平方根是 2.82842…,
由於返回類型是整數,小數部分將被捨去。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/sqrtx
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路
- 牛頓迭代法,參考這位網友:https://blog.csdn.net/chenrenxiang/article/details/78286599
代碼
func mySqrt(x int) int {
if x==0 {
return 0
}
//牛頓迭代法hh
var res float64
var times int
times = 100
res = float64(x)
for i:=0; i< times; i++ {
res = res - (res*res-float64(x))/(2*res)
}
return int(res)
}
debug
- x=0,考慮下吧