# Ternary number solution

• The idea is that the ternary number that is power of 3 will be something like 10,100,1000, etc, analogous to binary numbers that are powers of 2.

``````public boolean isPowerOfThree(int n) {
String s = Integer.toString(n, 3);
if (s.contains("2")) return false;
int result = Integer.valueOf(s, 2)&(Integer.valueOf(s, 2)-1);
return result==0&n>0?true:false;
}``````

• Haha, good idea. Nicer implementation, though:

``````public boolean isPowerOfThree(int n) {
return Integer.toString(n, 3).matches("10*");
}``````

• Very nice to use regex

• nice solution. It also shows how unfamiliar I am with Java built-in functions :(

• Could you explain your regex?

• @lusenii Seriously? That regex is about as basic as they get, plus you should be able to guess it from the context.

• Yeah your right I just looked it up. Sometimes you have to look stupid before you can be smart lol

• Interesting~

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