# Why does this solution not work?

• Shouldn't this be solvable with math using log/exponents rules?

``````public class Solution {
public boolean isPowerOfThree(int n) {

//Get the exponent value if 3 was the base
double x = Math.log(n) / Math.log(3);

//if the exponent is an integer than 3 could be the base and result is true
if (x == (int)x)
return true;
else
return false;

}
}``````

• Try this.

public class Solution {
public boolean isPowerOfThree(int n) {

``````    //Get the exponent value if 3 was the base
double x = Math.log(n) / Math.log(3);

//if the exponent is an integer than 3 could be the base and result is true

if (x<=(int)(x+0.1)+0.0000000001&&x>=(int)(x+0.1)-0.0000000001)
return true;
else
return false;

}
``````

}

• First of all, you need to take care of special cases, such as n=0.

Also, `log` operation tends to round off the result, so you `x` can be actually smaller `n` due to the round off error.

• First try take care of n == 0 case. Second you would want to round off the double value. A Math.round(x) should work.

• Because of double precision, below should work. +0.5 to make it round to the closest int

`````` public boolean isPowerOfThree(int n) {
double x = Math.log(n) / Math.log(3);
double diff = Math.abs(x -(int)(x+0.5));
return diff<=0.000001;
}``````

• This worked perfectly, thanks!. Accepted solution

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