LeetCode-633. 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 a2 + b2 = c.

Example 1:

1
2
3
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5

Example 2:

1
2
Input: 3
Output: False

題意

给一个数字 c,判断是否满足 a^2 + b^2 = c

思路

从 0 到 sqrt(c)之间进行遍历,检测剩下的数开方后是不是整数。

代码

1
2
3
4
5
6
7
8
9
boolean judgeSquareSum(int c) {
int limit = (int) Math.sqrt(c);
for (int n = 0; n <= limit; n++) {
double test = Math.sqrt(c - n * n);
if (test - (int)test == 0)
return true;
}
return false;
}

-------------本文结束感谢您的阅读-------------
Thank you for your encouragement