From 826f64b15c5a1a5b9b3abd8be2018fe8c047bb4c Mon Sep 17 00:00:00 2001 From: 0xff-dev <stevenshuang521@gmail.com> Date: Tue, 1 Apr 2025 09:24:23 +0800 Subject: [PATCH] Add solution and test-cases for problem 69 --- leetcode/1-100/0069.Sqrt-x/Solution.go | 12 +++++++++++ leetcode/1-100/0069.Sqrt-x/Solution_test.go | 23 +++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/leetcode/1-100/0069.Sqrt-x/Solution.go b/leetcode/1-100/0069.Sqrt-x/Solution.go index 760c706f7..db3608581 100644 --- a/leetcode/1-100/0069.Sqrt-x/Solution.go +++ b/leetcode/1-100/0069.Sqrt-x/Solution.go @@ -1,5 +1,7 @@ package Solution +import "sort" + func mySqrt(x int) int { r := x for r*r > x { @@ -7,3 +9,13 @@ func mySqrt(x int) int { } return r } + +func mySqrt1(x int) int { + idx := sort.Search(x, func(i int) bool { + return i*i >= x + }) + if idx*idx == x { + return idx + } + return idx - 1 +} diff --git a/leetcode/1-100/0069.Sqrt-x/Solution_test.go b/leetcode/1-100/0069.Sqrt-x/Solution_test.go index 81190b2c0..e2b89328e 100644 --- a/leetcode/1-100/0069.Sqrt-x/Solution_test.go +++ b/leetcode/1-100/0069.Sqrt-x/Solution_test.go @@ -27,3 +27,26 @@ func TestSolution(t *testing.T) { }) } } + +func TestSolution1(t *testing.T) { + // 测试用例 + cases := []struct { + name string + inputs int + expect int + }{ + {"1 test 1", 4, 2}, + {"2 test 2", 8, 2}, + } + + // 开始测试 + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + ret := mySqrt1(c.inputs) + if !reflect.DeepEqual(ret, c.expect) { + t.Fatalf("expected: %v, but got: %v, with inputs: %v", + c.expect, ret, c.inputs) + } + }) + } +}