LeetCode-326
Links:https://leetcode.com/problems/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?
思路:
1.用2^31次方内,最大的3的幂去除n取余…判断余数是否为0
2.用log()函数.判断n是3的多少次方(是不是一个整数),用log10()是因为精度问题.
代码1:
1 2 3 4 5 6 |
class Solution { public: bool isPowerOfThree(int n) { return n>0 && 1162261467%n==0; } }; |
代码2:
1 2 3 4 5 6 7 |
class Solution { public: bool isPowerOfThree(int n) { double asnlog = log10(n)/log10(3); return asnlog- int(asnlog)==0?true:false; } }; |
【LeetCode】326. Power of Three