367. 有效的完全平方数
import java.util.Scanner;
public class lc_367_solution1 {
public static boolean isPerfectSquare(int num) {
long temp = 1;
for(long i = 1; i <= num && temp <= num; i++)
{
temp = i * i;
if(temp == num)
{
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int num = sc.nextInt();
boolean res = isPerfectSquare(num);
System.out.println(res);
}
sc.close();
}
}
2. 代码二:数学计算(优选)
import java.util.Scanner;
public class lc_367_solution2 {
public static boolean isPerfectSquare(int num) {
int x = 1;
while(num > 0)
{
num -= x;
x += 2;
}
return num == 0 ? true : false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int num = sc.nextInt();
boolean res = isPerfectSquare(num);
System.out.println(res);
}
sc.close();
}
}
参考:
- 【宫水三叶】一题双解 :「二分」&「数学」
- 执行用时 : 0 ms , 在所有 C++ 提交中击败了 100.00% 的用户
- 有效的完全平方数



