zoukankan      html  css  js  c++  java
  • 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;
    		}		
    	}
    }


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

  • 相关阅读:
    网络文件传输方式
    ETL利器Kettle
    oracle 字符处理
    ORACLE临时表空间
    Count(*)或者Count(1)或者Count([列]) 区别
    Oracle trunc()函数的用法
    DATE 日期格式
    oracle 异常
    物化视图
    域名和端口
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824958.html
Copyright © 2011-2022 走看看