64. Power of Three

Given an integer, write a function to determine if it is a power of three.

Follow up:
Could you do it without using any loop / recursion?(待求解!!!!)

题目要求,判断给定的数字是否为3的幂数。如81返回true,71返回false。

/**
	 * 方法1:如果是非正数则返回false,否则return isPowerOfThree(n/3)
	 */
	public boolean isPowerOfThree(int n) {
		System.out.println("n = "+n);
        if(n<=0){
        	return false;
        }else{
        	if(n==1){
        		return true;
        	}else{
        		if(n%3 != 0){
        			return false;
        		}else{
        			return isPowerOfThree(n/3);
        		}
        		
        	}
        	
        }
    }
	
	/**
	 * 方法2:迭代做,n一直除3,如果除不尽则返回false
	 */
	public boolean isPowerOfThree2(int n) {
        if(n<=0){
        	return false;
        }else{
        	while(n>1){
        		if(n%3!=0){
        			return false;
        		}
        		n = n/3;
        	}
        	return true;
        }
    }
	
	/**
	 * 方法3:迭代做,n一直除3,如果除不尽则返回false
	 */
	public boolean isPowerOfThree3(int n) {
        if(n<=0){
        	return false;
        }else{
        	while(n>1 && n%3==0){
        		n = n/3;
        	}
        	System.out.println("n = "+n%3);
        	return n==1;
        }
    }



你可能感兴趣的:(64. Power of Three)