326. Power of Three

Easy

Given an integer, write a function to determine if it is a power of three.

Example 1:

Input: 27
Output: true

Example 2:

Input: 0
Output: false

Example 3:

Input: 9
Output: true

Example 4:

Input: 45
Output: false

Follow up:
Could you do it without using any loop / recursion?

package leetcode.easy;

public class PowerOfThree {
	public static void main(String[] args) {
		PowerOfThree sol = new PowerOfThree();
		int iterations = 1000000; // See table header for this value
		long startTime = System.currentTimeMillis(); // 获取开始时间
		for (int i = 0; i < iterations; i++) {
			sol.isPowerOfThree1(i);
		}
		long endTime = System.currentTimeMillis(); // 获取结束时间
		System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); // 输出程序运行时间

		startTime = System.currentTimeMillis(); // 获取开始时间
		for (int i = 0; i < iterations; i++) {
			sol.isPowerOfThree2(i);
		}
		endTime = System.currentTimeMillis(); // 获取结束时间
		System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); // 输出程序运行时间

		startTime = System.currentTimeMillis(); // 获取开始时间
		for (int i = 0; i < iterations; i++) {
			sol.isPowerOfThree3(i);
		}
		endTime = System.currentTimeMillis(); // 获取结束时间
		System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); // 输出程序运行时间

		startTime = System.currentTimeMillis(); // 获取开始时间
		for (int i = 0; i < iterations; i++) {
			sol.isPowerOfThree4(i);
		}
		endTime = System.currentTimeMillis(); // 获取结束时间
		System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); // 输出程序运行时间
	}

	public boolean isPowerOfThree1(int n) {
		if (n < 1) {
			return false;
		}

		while (n % 3 == 0) {
			n /= 3;
		}

		return n == 1;
	}

	public boolean isPowerOfThree2(int n) {
		return Integer.toString(n, 3).matches("^10*$");
	}

	public boolean isPowerOfThree3(int n) {
		return (Math.log10(n) / Math.log10(3)) % 1 == 0;
	}

	public boolean isPowerOfThree4(int n) {
		return n > 0 && 1162261467 % n == 0;
	}

	@org.junit.Test
	public void test() {
		System.out.println(isPowerOfThree1(27));
		System.out.println(isPowerOfThree1(0));
		System.out.println(isPowerOfThree1(9));
		System.out.println(isPowerOfThree1(45));
		System.out.println(isPowerOfThree2(27));
		System.out.println(isPowerOfThree2(0));
		System.out.println(isPowerOfThree2(9));
		System.out.println(isPowerOfThree2(45));
		System.out.println(isPowerOfThree3(27));
		System.out.println(isPowerOfThree3(0));
		System.out.println(isPowerOfThree3(9));
		System.out.println(isPowerOfThree3(45));
		System.out.println(isPowerOfThree4(27));
		System.out.println(isPowerOfThree4(0));
		System.out.println(isPowerOfThree4(9));
		System.out.println(isPowerOfThree4(45));
	}
}
01-01 06:00