Interview Check If n Is A Perfect Square

时间:2023-03-09 01:46:58
Interview Check If n Is A Perfect Square

Check if a given number is a perfect square with only addition or substraction operation.

eg. 25 returns true; 19 returns false.

Perfect square number 有一个特性,比如0,1,4,9,16,25 他们之间的间隔分别是1,3,5,7,9,每次间隔都是i+2.

所以每次往下减i, i 更新成i+2. 看最后结果是否为0即可。

import java.util.*;
public class isPerfectSquare{
public static void main(String [] args){
int num1 = 0;
int num2 = 1;
int num3 = 25;
int num4 = 19;
System.out.println(isPerfectSquare(num1));
System.out.println(isPerfectSquare(num2));
System.out.println(isPerfectSquare(num3));
System.out.println(isPerfectSquare(num4));
}
private static boolean isPerfectSquare(int n){
//1,4,9,16,25
//1+3+5+7+9
if(n<0){
return false;
}
int i = 1;
while(n>0){
n-=i;
i+=2;
}
if(n == 0){
return true;
}else{
return false;
}
}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。