326. Power of Three LeetCode解题报告
2016-01-13 17:48
405 查看
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?
解法一:采用循环,O(lg(N))的速度
解法二:采用递归方法
解法三
解法四
解法5
The code implements the base change rule of the logarithm. it basically looks at if base3 logarithm of the number is an integer or not.
Follow up:
Could you do it without using any loop / recursion?
解法一:采用循环,O(lg(N))的速度
class Solution { public: bool isPowerOfThree(int n) { if (n == 1 || n == 3 ) return true; if (n<3) return false; int i = 2; while(true) { if(pow(3,i) ==n) return true; else if (pow(3,i) > n) return false; else ++i; } } };
解法二:采用递归方法
class Solution { public: bool isPow3(int n, int step){ if(pow(3,step) == n) return true; else if(pow(3,step) > n) return false; else return isPow3(n,++step); } bool isPowerOfThree(int n) { int step = 0; return isPow3(n,step); } };
解法三
return n>0 ? !(1162261467%n):0;
解法四
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
bool isPowerOfThree(int n) { double logRes = log10(n)/log10(3); return (logRes - int(logRes) == 0) ? true : false; }
The code implements the base change rule of the logarithm. it basically looks at if base3 logarithm of the number is an integer or not.
相关文章推荐
- 关于PowerDesigner初体验的使用介绍
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- usb接口只读原理及应用
- CentOS 5.x 默认启动的服务内容
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- power builder管理导入sybase数据库数据