diff --git a/Algorithms/0633. Sum of Square Numbers/633. Sum of Square Numbers.go b/Algorithms/0633. Sum of Square Numbers/633. Sum of Square Numbers.go new file mode 100644 index 00000000..a1f22e68 --- /dev/null +++ b/Algorithms/0633. Sum of Square Numbers/633. Sum of Square Numbers.go @@ -0,0 +1,17 @@ +package leetcode + +import "math" + +func judgeSquareSum(c int) bool { + low, high := 0, int(math.Sqrt(float64(c))) + for low <= high { + if low*low+high*high < c { + low++ + } else if low*low+high*high > c { + high-- + } else { + return true + } + } + return false +} diff --git a/Algorithms/0633. Sum of Square Numbers/633. Sum of Square Numbers_test.go b/Algorithms/0633. Sum of Square Numbers/633. Sum of Square Numbers_test.go new file mode 100644 index 00000000..aebd61c2 --- /dev/null +++ b/Algorithms/0633. Sum of Square Numbers/633. Sum of Square Numbers_test.go @@ -0,0 +1,73 @@ +package leetcode + +import ( + "fmt" + "testing" +) + +type question633 struct { + para633 + ans633 +} + +// para 是参数 +// one 代表第一个参数 +type para633 struct { + one int +} + +// ans 是答案 +// one 代表第一个答案 +type ans633 struct { + one bool +} + +func Test_Problem633(t *testing.T) { + + qs := []question633{ + + question633{ + para633{1}, + ans633{true}, + }, + + question633{ + para633{2}, + ans633{true}, + }, + + question633{ + para633{3}, + ans633{false}, + }, + + question633{ + para633{4}, + ans633{true}, + }, + + question633{ + para633{5}, + ans633{true}, + }, + + question633{ + para633{6}, + ans633{false}, + }, + + question633{ + para633{104976}, + ans633{true}, + }, + // 如需多个测试,可以复制上方元素。 + } + + fmt.Printf("------------------------Leetcode Problem 633------------------------\n") + + for _, q := range qs { + _, p := q.ans633, q.para633 + fmt.Printf("【input】:%v 【output】:%v\n", p, judgeSquareSum(p.one)) + } + fmt.Printf("\n\n\n") +} diff --git a/Algorithms/0633. Sum of Square Numbers/README.md b/Algorithms/0633. Sum of Square Numbers/README.md new file mode 100755 index 00000000..b581b1ab --- /dev/null +++ b/Algorithms/0633. Sum of Square Numbers/README.md @@ -0,0 +1,28 @@ +# [633. Sum of Square Numbers](https://leetcode.com/problems/sum-of-square-numbers/) + + +## 题目: + +Given a non-negative integer `c`, your task is to decide whether there're two integers `a` and `b` such that a^2 + b^2 = c. + +**Example 1:** + + Input: 5 + Output: True + Explanation: 1 * 1 + 2 * 2 = 5 + +**Example 2:** + + Input: 3 + Output: False + + +## 题目大意 + +给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c。 + + +## 解题思路 + +- 给出一个数,要求判断这个数能否由由 2 个完全平方数组成。能则输出 true,不能则输出 false。 +- 可以用二分搜索来解答这道题。判断题意,依次计算 `low * low + high * high` 和 c 是否相等。从 [1, sqrt(n)] 区间内进行二分,若能找到则返回 true,找不到就返回 false 。