326. Power of Three

Question
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

&lt;LeetCode OJ&gt; 326. Power of Three的更多相关文章

  1. 【leetcode❤python】326. Power of Three

    #-*- coding: UTF-8 -*- class Solution(object):    def isPowerOfThree(self, n):        if n<=0:    ...

  2. leetcode 326. Power of Three(不用循环或递归)

    leetcode 326. Power of Three(不用循环或递归) Given an integer, write a function to determine if it is a pow ...

  3. [LeetCode] 231 Power of Two && 326 Power of Three && 342 Power of Four

    这三道题目都是一个意思,就是判断一个数是否为2/3/4的幂,这几道题里面有通用的方法,也有各自的方法,我会分别讨论讨论. 原题地址:231 Power of Two:https://leetcode. ...

  4. 39. leetcode 326. Power of Three

    326. Power of Three Given an integer, write a function to determine if it is a power of three. Follo ...

  5. LeetCode OJ 题解

    博客搬至blog.csgrandeur.com,cnblogs不再更新. 新的题解会更新在新博客:http://blog.csgrandeur.com/2014/01/15/LeetCode-OJ-S ...

  6. 【LeetCode OJ】Interleaving String

    Problem Link: http://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 ...

  7. 【LeetCode OJ】Reverse Words in a String

    Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...

  8. LeetCode OJ学习

    一直没有系统地学习过算法,不过算法确实是需要系统学习的.大二上学期,在导师的建议下开始学习数据结构,零零散散的一学期,有了链表.栈.队列.树.图等的概念.又看了下那几个经典的算法——贪心算法.分治算法 ...

  9. LeetCode OJ 297. Serialize and Deserialize Binary Tree

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

随机推荐

  1. Blender之Property

    目标 [x] 总结Blender插件之属性bpy.props 总结 bpy.props bpy.props模块用来扩展Blender内置数据的属性. 这些函数的结果用于为用Blender注册的类分配属 ...

  2. BZOJ 4563 错排+高精度

    思路: 把障碍移到对角线 就发现 这是个错位排列问题 用错排公式即可解 s[i]=(s[i-1]+s[i-2])*i //By SiriusRen #include <cstdio> #i ...

  3. 小白写的一个ASP.NET分页控件,仅供娱乐

    无聊,第一次写博客,自己动手写了一个分页控件.由于我是新手,有很多地方写得不够好,希望各位大牛多多指正.哈哈哈 /// <summary> /// 分页控件 /// </summar ...

  4. Spring boot (12) tomcat jdbc连接池

    默认连接池 tomcat jdbc是从tomcat7开始推出的一个连接池,相比老的dbcp连接池要优秀很多,spring boot将tomcat jdbc作为默认的连接池,只要在pom.xml中引入了 ...

  5. java程序员级别划分

    IT路虽好,却难走.1级   为会基本语法 大学里的JAVA教程 能及格 2级   自己可以写个 俄罗斯方块,扫雷,贪吃蛇, 拼图之类的小游戏 3级   能够进手机游戏CP,SP公司,做手机游戏 或者 ...

  6. python3:语法变动 及新特性

    python3.0 对python2.x 升级后重大语法变动,幸好留下2.7.6及后续2版本,保持一些语法兼容. 原始地址:http://hi.baidu.com/jxq61/item/3a24883 ...

  7. java mongodb 使用MongoCollection,BasicDBObject 条件查询

    废话不说,上代码 //链接数据库 MongoClient mongoClient = new MongoClient( "172.26.xxx.xxx" , 27017 ); Mo ...

  8. Tomcat jsp页面显示有问题

    1.干掉tomcat下的work文件夹里面的东西,让jsp文件重新编译,相当于清楚缓存 2.work 里面是 jsp 编译的类 ,只要jsp 被访问了,就会被编译,就会生成相应的类 3.tomcat下 ...

  9. javaee IO流作业

    package Zy; import java.io.Serializable; public class Student implements Serializable{ private stati ...

  10. PAT_A1122#Hamiltonian Cycle

    Source: PAT A1122 Hamiltonian Cycle (25 分) Description: The "Hamilton cycle problem" is to ...