Leetcode: Power of Three

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

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

Recursion:

1 public class Solution {
2     public boolean isPowerOfThree(int n) {
3         if (n <= 0) return false;
4         if (n == 1) return true;
5         else if (n%3 == 0) return isPowerOfThree(n/3);
6         else return false;
7     }
8 }

Iteration:

 1 public class Solution {
 2     public boolean isPowerOfThree(int n) {
 3         if (n <= 0) return false;
 4         while (n != 1) {
 5             if (n%3 != 0) break;
 6             n /= 3;
 7         }
 8         return n==1;
 9     }
10 }

Math: https://leetcode.com/discuss/78532/a-summary-of-all-solutions

It's all about MATH...

Method 1

Find the maximum integer that is a power of 3 and check if it is a multiple of the given input. (related post)

1 public boolean isPowerOfThree(int n) {
2     return n>0 && Math.pow(3, (int)(Math.log(0x7fffffff)/Math.log(3)))%n==0;
3 }

Note that

Math.pow(3, (int)(Math.log(0x7fffffff)/Math.log(3)))

returns the maximum integer that is a power of 3

Method 2

If log10(n) / log10(3) returns an int, then n is a power of 3. (original post). But be careful here, you cannot use log (natural log) here, because it will generate round off error.

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

 

原文地址:https://www.cnblogs.com/EdwardLiu/p/5115390.html