SumOfSquareNumbers [source code]
public class SumOfSquareNumbers {
static
/******************************************************************************/
public class Solution {
public boolean judgeSquareSum(int c) {
if (isSquare(c)) return true;
for (int i = 1; i <= c / 2; i++) {
if (isSquare(i) && isSquare(c - i)) return true;
}
return false;
}
public boolean isSquare(int n) {
int root = (int) Math.sqrt(n);
return root * root == n;
}
}
/******************************************************************************/
public static void main(String[] args) {
SumOfSquareNumbers.Solution tester = new SumOfSquareNumbers.Solution();
int[] inputs = {
5, 4, 3, 0, 2,
};
for (int i : inputs) {
System.out.println(i + " -> " + tester.judgeSquareSum(i));
}
}
}
这个代码本身是没有问题的, 不过最后被999999999超时了;
Problem Description
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
Difficulty:Easy
Total Accepted:5K
Total Submissions:15.9K
Contributor: Stomach_ache
Companies
linkedin
Related Topics
math
Similar Questions
Valid Perfect Square