<LeetCode OJ> 326. Power of Three

原创 2016年01月08日 22:44:49

326. Power of Three

Total Accepted: 1159 Total Submissions: 3275 Difficulty: Easy

判断给定整数是否是3的某次方。

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?

完成此题,能否不用迭代或者循环?(<--这是以前的错误翻译,惭愧。

正确的应该是:完成此问题能否不用任何形式的循环和递归?)



分析:DONE

最简单的方法,反复迭代(即循环,但是题目不建议)

简单分析:

a)3^x,不管x正或者负,这个值一定大于0

b)如果一个数是3的x次方那么,反复除以3,最终一定等于1,return true

c)否则不是满足要求的数,return false

时间复杂度:O(lg(n)),空间复杂度:O(1)

class Solution {
public:
    bool isPowerOfThree(int n) {
        int num=n;   
        while(num>0 && num%3==0)
            num/=3;
        return num==1;    
    }
};


2,和上面的思想一样:递归形式的解法(题目不建议)

时间复杂度:O(lg(n)),空间复杂度:O(lg(n))

class Solution {
public:
   
    bool isPow3(int n,int step) {
        if(pow(3,step)==n)  
                return true;  
        if(pow(3,step)>n)  
                return false;  
        if(pow(3,step)<n)  
                return isPow3(n,++step); 
    }
    bool isPowerOfThree(int n) {
        int step=0;
        return isPow3(n,step);
    }
};


不用任何循环:(参考讨论区)

3,任何一个3的x次方一定能被int型里最大的3的x次方整除,如下所示:

return n>0?!(1162261467 % n):0;


4,或者直接列举:

因为n是int型整数,所以其内满足要求的数还不到32个(2的x次方才32个),所以可以直接列举

class Solution {
public:
    bool isPowerOfThree(int n) {
        return (n == 1 || n == 3 || n == 9 || n == 27 || n == 81 || n == 243 || n == 729 || n == 2187 || n == 6561 || n == 19683 || n == 59049 || n == 177147 || n == 531441 || n == 1594323 || n == 4782969 || n == 14348907 || n == 43046721 || n == 129140163 || n == 387420489 || n == 1162261467);
    }
};


5,log函数

一个基本的事实就是如果n是3的x次方,那么以3为低对数后一定是一个整数,否则不是

class Solution {
public:
    bool isPowerOfThree(int n) {
        double res = log10(n) / log10(3);  //有精度问题,不要用以指数2.718为低的log函数
        return (res - int(res) == 0) ? true : false;
    }
};


附带讨论区一篇原文:

Well, this problem doesn't seem to be quite interesting or worthwhile to think about at a first glance. I had the same feeling at the beginning. However, after seeing a couple of posts, I saw a couple of interesting ways. So here is a summary post and hope you learn something from others' solutions.

Two trivial solutions first:

Recursive Solution

public boolean isPowerOfThree(int n) {
    return n>0 && (n==1 || (n%3==0 && isPowerOfThree(n/3)));
}

Iterative Solution

update following Stefan's answer below:

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

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

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)

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

Or simply hard code it since we know maxPowerOfThree = 1162261467:

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

It is worthwhile to mention that Method 1 works only when the base is prime. For example, we cannot use this algorithm to check if a number is a power of 4 or 6 or any other composite number.

Method 2

If log10(n) / log10(3) returns an int (more precisely, a double but has 0 after decimal point), 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 for n=243. This is more like a coincidence. I mean when n=243, we have the following results:

log(243) = 5.493061443340548    log(3) = 1.0986122886681098
   ==> log(243)/log(3) = 4.999999999999999

log10(243) = 2.385606273598312    log10(3) = 0.47712125471966244
   ==> log10(243)/log10(3) = 5.0

This happens because log(3) is actually slightly larger than its true value due to round off, which makes the ratio smaller.

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

Method 3 related post

public boolean isPowerOfThree(int n) {
    return n==0 ? false : n==Math.pow(3, Math.round(Math.log(n) / Math.log(3)));
}

Method 4 related post

public boolean isPowerOfThree(int n) {
    return n>0 && Math.abs(Math.log10(n)/Math.log10(3)-Math.ceil(Math.log10(n)/Math.log10(3))) < Double.MIN_VALUE;
}

Cheating Method

This is not really a good idea in general. But for such kind of power questions, if we need to check many times, it might be a good idea to store the desired powers into an array first. (related post)

public boolean isPowerOfThree(int n) {
    int[] allPowerOfThree = new int[]{1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467};
    return Arrays.binarySearch(allPowerOfThree, n) >= 0;
}

or even better with HashSet:

public boolean isPowerOfThree(int n) {
    HashSet<Integer> set = new HashSet<>(Arrays.asList(1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467));
    return set.contains(n);
}

New Method Included at 15:30pm Jan-8th

Radix-3 original post

The idea is to convert the original number into radix-3 format and check if it is of format 10*where 0* means k zeros with k>=0.

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




注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50485622

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895
版权声明:本文为EbowTang原创文章,后续可能继续更新本文。如果转载,请务必复制本文末尾的信息!

leetcode笔记:Power of Three

题目的大意很简单,给出一个整数,判断这个整数是不是3的整数次幂。下面提示尽量不适用循环和递归来实现,因此这里给出两种实现方法,其中第一种循环方式的耗时更少。...
  • liyuefeilong
  • liyuefeilong
  • 2016年01月10日 17:17
  • 3016

Power of Three

题目描述: Given an integer, write a function to determine if it is a power of three. Follow up: Cou...
  • yeshiwu
  • yeshiwu
  • 2016年06月14日 17:19
  • 345

[Leetcode]Move Zeroes

Given an array nums, write a function to move all 0's to the end of it while maintaining the relati...
  • Javasus
  • Javasus
  • 2015年10月10日 12:51
  • 2833

[LeetCode 326] Power of Three

Given an integer, write a function to determine if it is a power of three. Follow up: Could you ...
  • sbitswc
  • sbitswc
  • 2016年01月13日 17:11
  • 3998

326. Power of Three [easy] (Python)

题目链接https://leetcode.com/problems/power-of-three/题目原文 Given an integer, write a function to determ...
  • coder_orz
  • coder_orz
  • 2016年05月26日 11:38
  • 1513

【Leetcode】:326. Power of Three 问题 in JAVA

Given an integer, write a function to determine if it is a power of three. Follow up: Could yo...
  • u013564276
  • u013564276
  • 2016年05月07日 15:46
  • 629

Non Power of Two Textures 无二次幂限制的纹理

无二次幂限制的纹理(Non-Power-of-Two Textures)   OpenGL仅支持分辨率为2mx2n的纹理。但现在我们可以使用“无二次幂限制”的纹理。   OpenGL only...
  • wolf96
  • wolf96
  • 2015年09月04日 14:40
  • 1851

[机器学习入门] 李弘毅机器学习笔记-7 (Brief Introduction of Deep Learning;深度学习简介)

[机器学习入门] 李弘毅机器学习笔记-7 (Brief Introduction of Deep Learning;深度学习简介) PDF VIDEOUps and downs of Deep...
  • soulmeetliang
  • soulmeetliang
  • 2017年06月05日 19:32
  • 1708

Leetcode全求和问题

目录 1、编号1 Two Sum Given an array of integers, find two numbers such that they add up to a specifi...
  • wangxiaojun911
  • wangxiaojun911
  • 2014年02月04日 10:29
  • 9975

leetcode326. Power of Three

326. Power of ThreeGiven an integer, write a function to determine if it is a power of three.Follow ...
  • rxt2012kc
  • rxt2012kc
  • 2017年03月30日 22:42
  • 119
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:<LeetCode OJ> 326. Power of Three
举报原因:
原因补充:

(最多只允许输入30个字)