【LeetCode】Power of Three 解题报告

Power of Three

[LeetCode]

https://leetcode.com/problems/power-of-three/

Total Accepted: 38705 Total Submissions: 105634 Difficulty: Easy

Question

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?

Ways

第一感觉好简单!一看followup说能不能不用递归和循环。那肯定是数学问题了。

想着找规律吧,只找到一个规律,9以上的3的幂各位的和都能被9整除……但是比如18,虽然1+8也能被9整除,但是不是3的倍数。

没辙,看别人怎么写的。好像也不是太聪明啊!

取对数。看一个数以3为底的对数是否为整数。好吧还是挺聪明的。

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

    }
}

AC:20ms

还有一种方法是说,先找出最大的3的幂的int,再看n能否整除这个数。效率应该比这个高,没有试。可以参考:

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

Date

2016/5/1 16:47:54

你可能感兴趣的:(LeetCode)