leetcode_326. Power of Three分析
2016-11-22 11:49
381 查看
类似的题解详见:
leetcode_232. Power of Two分析
leetcode_342. Power of Four分析
题目链接
【题目】
Given an integer, write a function to determine if it is a power of three.
【分析】
解法1:
一般做法
解法2:
由于输入是int,正数范围是0-2**31,在此范围中允许的最大的3的次方数为319=1162261467,那么我们只要看这个数能否被n整除即可
解法3:
根据解法2我们很容易想到的解法,就是将3**0 到3**19打表出来
解法4:
这是discuss中一种比较巧妙地方法,利用我们数学中的换底公式
log a (b) = log c (b) / log c (a)
如果n是3的倍数,则log 3 (n)一定是整数,我们利用换底公式可以写为log 3 (n) = log 10 (n) / log 10 (3)
在c++中判断数字a是否为整数,我们可以用 a - int(a) == 0 来判断
leetcode_232. Power of Two分析
leetcode_342. Power of Four分析
题目链接
【题目】
Given an integer, write a function to determine if it is a power of three.
【分析】
解法1:
一般做法
class Solution { public: bool isPowerOfThree(int n) { while (n && n % 3 == 0) { n /= 3; } return n == 1; } };
解法2:
由于输入是int,正数范围是0-2**31,在此范围中允许的最大的3的次方数为319=1162261467,那么我们只要看这个数能否被n整除即可
class Solution { public: bool isPowerOfThree(int n) { return (n > 0 && 1162261467 % n == 0); } };
解法3:
根据解法2我们很容易想到的解法,就是将3**0 到3**19打表出来
class Solution { public: bool isPowerOfThree(int n) { int power_list[20] = {1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467}; for( int num:power_list ) if( num == n ) return true; return false; } };
解法4:
这是discuss中一种比较巧妙地方法,利用我们数学中的换底公式
log a (b) = log c (b) / log c (a)
如果n是3的倍数,则log 3 (n)一定是整数,我们利用换底公式可以写为log 3 (n) = log 10 (n) / log 10 (3)
在c++中判断数字a是否为整数,我们可以用 a - int(a) == 0 来判断
class Solution { public: bool isPowerOfThree(int n) { return (n > 0 && int(log10(n) / log10(3)) - log10(n) / log10(3) == 0); } };
相关文章推荐
- [leetcode] 326. Power of Three 解题报告
- Leetcode 326. Power of Three
- Leetcode 231. Power of Two & 326. Power of Three & 342. Power of Four
- Leetcode 326. Power of Three
- 【Leetcode】:326. Power of Three 问题 in JAVA
- leetcode 326. Power of Three(不用循环或递归)
- leetcode 326. Power of Three
- leetcode 326. Power of Three
- LeetCode *** 326. Power of Three
- LeetCode 326. Power of Three
- Leetcode 326. Power of Three
- leetcode 326. Power of Three
- LeetCode ||326. Power of Three
- LeetCode 326. Power of Three
- leetcode 每日一题 231. Power of Two 326. Power of Three
- 326. Power of Three LeetCode解题报告
- LeetCode-326. Power of Three
- [LeetCode]326. Power of Three
- LeetCode---PowerOfTwo、PowerOfThree、 PowerOfFour解题分析
- [leetcode] 326. Power of Three