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;
    		}		
    	}
    }


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

  • 相关阅读:
    配置centOS下的Python
    linux基础命令2
    linux基础命令1
    linux常用命令(运维用到)
    Lab 10-2
    Lab 10-1
    Lab 9-3
    archlinux 装完系统连接 wifi 网络
    arch Linux(二)
    arch Linux 安装完,无法通过 SSH 远程连接 root 用户问题
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824958.html
Copyright © 2011-2022 走看看