Sum of Square Numbers
2017-07-03 本文已影响0人
Jarhot
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
public boolean judgeSquareSum(int c) {
int left = 0;
for (int right = (int) Math.pow(2, 0.5) * (int) Math.pow(c, 0.5); right >= 0; right--) {
while (right >= left) {
int count = (int) (Math.pow(left, 2) + Math.pow(right, 2));
if (count > c) {
break;
} else if (count < c) {
left++;
} else if (count == c) {
return true;
}
}
}
return false;
}
第二种时间超时
public boolean judgeSquareSum(int c) {
for (int i = 0; i * i <= c; i++) {
int left = c - i * i;
int sqleft = (int) Math.pow(left, 0.5);
if (sqleft * sqleft == left) {
return true;
}
}
return false;
}