LeetCode 326. 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?


题目标签:Math

  题目要我们判断一个数字 是否是 3^n;如果是不能利用loop的话,那么就需要特殊方法。

  这里有一个比较特别的方法,因为给的数字是int,所以3^19 是int 里面最大的,只要利用3^19 % n == 0 来判断 n 是不是 power of three。

Java Solution:

Runtime beats 11.22% 

完成日期:06/16/2017

关键词:math

关键点:利用int里最大的3^19

1 class Solution 
2 {
3     public boolean isPowerOfThree(int n) 
4     {
5         // 1162261467 is 3^19, 3^20 is bigger than int
6         return (n > 0 && 1162261467 % n == 0);
7     }
8 }

参考资料:https://leetcode.com/problems/power-of-three/discuss/77856/1-line-java-solution-without-loop-recursion

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

原文地址:https://www.cnblogs.com/jimmycheng/p/8408555.html