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?

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

 

题意:判断给定的数是否为3的n次方
follow up:要求不使用循环或递归

方法一:直接判断

public boolean isPowerOfThree(int n) {
        if(n <= 0)
            return false;
        while(n > 1){
            if(n % 3 != 0)
                return false;
            n /= 3;
        }
        return true;
    }

没有想出不使用循环的解决方法,最后参考LeetCode提供的参考答案

方法二:将给定数n转换成3进制形式,再判断转换的3进制是否为高位为1,低位全为0的形式,是该形式则n是3的次方数;否则不是。

原理同Power Of Two的方法:http://www.cnblogs.com/zeroingToOne/p/8186009.html

实现:

Integer类的:static String toString(int i, int radix)方法:返回10进制i的radix进制形式。将给定数n转换为3进制;
String类的:boolean matches(String regex) 方法:返回此字符串是否匹配给定的正则表达式。判断n的3进制形式是否满足条件

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

方法三:由于输入的是int型,正数范围为0~2^31,在此范围内,3的最大次方数为3^19 = 11622 61467.因此只要看3^19能否被给定的数n整除即可。

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

方法四:

利用Math类的log10(double a)方法,返回 double 值的底数为 10 的对数。
只需要判断i是否为整数即可。

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

 

posted @ 2018-01-06 14:49  zeroingToOne  阅读(256)  评论(0编辑  收藏  举报