Description
Given an integer, write a function to determine if it is a power of three.
Example
Example 1:
Input: 27
Output: true
Example 2:
Input: 45
Output: false
Solving
Converting the input into a ternary number. It’s a power of three only when it likes “1”, “10”, “100”, “1000”, etc. Regular Expression could represent all the conditions.
class Solution {
public boolean isPowerOfThree(int n) {
return Integer.toString(n, 3).matches("^10*$");
}
}