633. sum of square numbers 实现 参考

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.

  • Example 1:

    1
    2
    3
    Input: 5
    Output: True
    Explanation: 1 * 1 + 2 * 2 = 5
  • Example 2:

    1
    2
    Input: 3
    Output: False

给定一个正整数c,判断是否存在两个数使得a^2+b^2=c。

实现

  • java

使用双指针来判断即可.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public boolean (int c) {

for (int i = 0 ,j = (int) Math.sqrt(c); i <= j;){
if ( i * i + j * j == c){
return true;
}
if ( i * i + j * j > c){
j -- ;
continue;
}
if ( i * i + j * j < c){
i ++ ;
continue;
}
}
return false;
}

参考