LeetCode 633
Sum of Square Numbers
- Problem Description:
判断一个非负整数能否分解成两个整数的平方和。
具体的题目信息:
https://leetcode.com/problems/sum-of-square-numbers/description/ - Solution: 如果按照平常思路双循环的话会严重超时,下面介绍两种看到的方法。
方法一:
class Solution {
public:
bool judgeSquareSum(int c) {
if (c == 0) return true;
for (int i = 0; i <= sqrt(c); i++) {
int b = c-i*i;
if (sqrt(b) == int(sqrt(b)))
return true;
}
return false;
}
};
方法二:
class Solution {
public:
bool judgeSquareSum(int c) {
int i = 0, j = sqrt(c);
while(i <= j) {
int sum = i*i+j*j;
if (c == sum) {
return true;
} else if (c < sum) {
j--;
} else {
i++;
}
}
return false;
}
};