给定一个非负整数 c
,你要判断是否存在两个整数 a
和 b
,使得 a2 + b2 = c
/**
* Created with IntelliJ IDEA.
* Version : 1.0
* Author : cunyu
* Email : cunyu1024@foxmail.com
* Website : https://cunyu1943.github.io
* Date : 2020/3/20 9:49
* Project : LeetCode
* Package : PACKAGE_NAME
* Class : SixHundredThirtThree
* Desc : 633.平方数之和
*/
public class SixHundredThiryThree {
public static void main(String[] args) {
SixHundredThiryThree sixHundredThiryThree = new SixHundredThiryThree();
int[] array = {3,5};
for(int item:array){
// System.out.println(item);
System.out.println(sixHundredThiryThree.judgeSquareSum(item));
}
}
public boolean judgeSquareSum(int c) {
// c为非负整数,则若c为负直接返回false
if (c < 0){
return false;
}
// 取c的平方根,并将其强制转换为不大于平方根值的最大整数
int flag = (int) Math.sqrt(c);
int i = 0;
while (i <= flag){
if ((i*i + flag*flag) == c){
return true;
} else if ((i * i + flag * flag) < c) {
i++;
}else {
flag--;
}
}
return false;
}
}
[1]
633. 平方数之和: https://leetcode-cn.com/problems/sum-of-square-numbers/