From 1360e366bf056d9f27aea46e0ade099342173460 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9B=B7=E7=B3=BB=E6=B3=A1=E6=B3=A1?= Date: Fri, 1 Nov 2019 10:27:30 +0800 Subject: [PATCH] Add Solution2.go for 0069.Sqrt(x) --- solution/0069.Sqrt(x)/Solution2.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 solution/0069.Sqrt(x)/Solution2.go diff --git a/solution/0069.Sqrt(x)/Solution2.go b/solution/0069.Sqrt(x)/Solution2.go new file mode 100644 index 0000000000000..c4379d8b011b1 --- /dev/null +++ b/solution/0069.Sqrt(x)/Solution2.go @@ -0,0 +1,14 @@ +func mySqrt(x int) int { + precision := 0.9 // 计算精度, 但 LeetCode 中要求返回 int 所以可以偷懒将误差 < 0.9 即可(不使用 1.0 是因为浮点型的精度问题), 追求精度可使用 0.0001 + guess, check := 1.0, 0.0 +calc: + guess = (float64(x)/guess + guess) / 2 + check = guess*guess - float64(x) + if check < 0 { + check = 0 - check + } + if check > precision { + goto calc + } + return int(guess) +}