3^19 is the largest power of three within the range of signed int. A remainder of 0 means n is a divisor of 3^19 and therefore a power of three.
1 2 3 4 5
publicclassSolution{ publicbooleanisPowerOfThree(int n){ return n > 0 && 1162261467 % n == 0; } }
1 2 3 4 5 6 7
// find the maximum power of 3 first publicclassSolution{ publicbooleanisPowerOfThree(int n){ int maxPower = (int) Math.pow(3, (int)(Math.log(0x7fffffff) / Math.log(3))); return n > 0 && maxPower % n == 0; } }
1 2 3 4 5 6 7 8 9
publicclassSolution{ publicbooleanisPowerOfThree(int n){ if (n <= 0 ){returnfalse;} // n is a power of three if and only if i is an integer. // In Java, we check if a number is an integer by taking // the decimal part (using % 1) and checking if it is 0. return (Math.log10(n) / Math.log10(3)) % 1 == 0; } }