Java Solution : Using Log < Solution to fix the error getting for 243 >


  • 1
    P
    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;
    	}

  • 1
    M

    why does this solution can avoid the error? Could you give more explanations?


  • 0
    P

    Basically if we dont round up the value it will end up in the error as the difference would be .000000001. So basically multiplying and dividing by 1000 rounds up to 3 digit.
    Other easy way to solve it is use Math.log10.


Log in to reply
 

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