题目介绍
给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
示例1
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5
示例2
输入: 3
输出: False
解题思路
其实这道题跟之前遇到过的双指针题类似,本质也还是利用0和结尾双指针,关键在于尾部指针的选取,这里便采取所求数的平方根作为尾指针,同时因为不需要考虑符号,可以设置为unsigned int型。
代码如下
bool judgeSquareSum(int c){
unsigned int min = 0, max = (int)sqrt(c);
while(min<=max){
if(min*min+max*max == c){
return 1;
}
else if(min*min+max*max<c){
min++;
}
else{
max--;
}
}
return 0;
}
而同样,unsigned的使用也缩减了所需要的内存。