问题:ide
Given a non-negative integer c
, your task is to decide whether there're two integers a
and b
such that a^2 + b^2 = c.spa
Example 1:指针
Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5
Example 2:code
Input: 3 Output: False
解决:ci
① 使用双指针查找是否存在知足条件的值。耗时12msio
public class Solution {
public boolean judgeSquareSum(int c) {
if (c < 0) return false;
int left = 0;
int right = (int)Math.sqrt(c);
while (left <= right) {
int sum = left * left + right * right;
if (sum < c) {
left ++;
} else if (sum > c) {
right --;
} else {
return true;
}
}
return false;
}
}class
② 因为a*a+b*b=c,因此只须要从0到sqrt(c)遍历,求得c-i*i的剩余值,并对其进行开方,判断它是不是一个整数,如果,返回true;不然,返回false。遍历
public class Solution { //25ms
public static boolean judgeSquareSum(int c) {
for (int i = 0;i <= Math.sqrt(c);i ++)
if (Math.floor(Math.sqrt(c - i * i)) == Math.sqrt(c - i * i)) return true;//Math.floor()向下取整
return false;
}
}static
③ 进化版while
public class Solution { //22ms
public boolean judgeSquareSum(int c) {
for(int i = 0;i <= Math.sqrt(c);i ++){
if((int)Math.sqrt(c - i * i) == Math.sqrt(c - i * i)) return true; } return false; } }