您的位置:首页 > 其它

LeetCode 633 Sum of Square Numbers

2017-09-13 14:54 363 查看
题目:

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:

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


Example 2:

Input: 3
Output: False

题目链接
题意:

给一个非负的整数c,判断是否存在两个整数a,b满足a2 +
b2 =
c。

c是非负的,所以a和b的取值可以为0,所以a和b取值应该是[0, sqrt(c)],从0到sqrt(c)枚举一遍,假如c-a*a开平方后可以整除1,那么说明此时的a,b满足条件。

代码如下:

class Solution {
public:
bool judgeSquareSum(int c) {
int temp = sqrt(c);
for (int i = 0; i <= temp; i ++) {
int j = c - i * i;
if (fmod(sqrt(j), 1.00) != 0) {
continue;
}
return true;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: