JAVA----------------Easy Version To Understand!!!!!!!!!!!


  • 20
    H
    	public static boolean isPowerOfThree(int n) {
    	if (n <= 0)
    		return false;
    	double r = Math.log10(n) / Math.log10(3);
    	if (r % 1 == 0)
    		return true;
    	else
    		return false;
    }

  • 0
    N

    I tried to use log(n)/log(3) instead, but it didn't work. Do you know what's the different between using base 10 and base e?


  • 0
    H

    if you replace log10 function with log then it will fail the tests because of precision error. That is,it will generate round off error for n=243.


  • 3
    P

    To avoid round off error a small twist

     public boolean isPowerOfThree(int n) {
            if (n == 3 || n == 1) {
    			return true;
    		}
    		if(n%3!=0){
    			return false;
    		}
    		double val = Math.log(n) / Math.log(3);
    		double rounded = (double) Math.round(val * 10000) / 10000;
    		if (Math.ceil(val) - rounded == 0) {
    			return true;
    		}
    		return false;
    	}

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.