leetcode-326-Power of Three

leetcode-326-Power of Three

题目描述:

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?

 

要完成的函数:

bool isPowerOfThree(int n) 

说明:

1、这道题给定一个整数n,要求判断n是不是3的整数次幂,比如27是3的3次幂,81是3的4次幂,这些都要返回true。尽量不用循环或递归来完成。

2、循环或递归的做法比较容易实现,这里就不列举出来了,就是不断地除以3,直到最后为1就返回true,不然就返回false。

笔者最开始想到log的方法,log3(n)如果为整数,那么就返回true。但后来想到log的实现,其实也是泰勒展开,循环计算,也是很费时间的。

之后想到了之前做过的题目。在int型整数,一共32位里面,3的整数次幂最大是3^19,所以用3^19%n==0来判断。如果能整除的话,说明n的因子都是3,所以n是3的整数次幂。

代码如下:

    bool isPowerOfThree(int n) 
    {
       if(n<=0||n>1162261467)
           return false;
        return !(1162261467%n);
    }

如果n小于等于0或者大于3^19,那么返回false。如果大于0,那么判断能不能用3^19来整除,如果可以就返回true,如果不行就返回false。

上述代码实测78ms,beats 71.76% of cpp submissions。

笔者还看到了有人列举出了所有的(3^19之内)3的整数次幂,然后逐个判断,也是有点神奇。