problem:
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
Example 3:
Input: 9
Output: true
Example 4:
Input: 45
Output: false
tip:
判断一个数是否是3的幂级数。
与231题比较,2的幂次方刚好是二进制数最高位为1其他位为0,而3的幂次方则没有规律。
solution:
1.递归求解
class Solution {
public:
bool isPowerOfThree(int n) {
if(n==0) return false;
if(n==1) return true;
if(n%3!=0) return false;
if(n/3==1) return true;
return isPowerOfThree(n/3);
}
};
2.看了其他的帖子,效率都不是很高、