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?
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
判断一个数是否为3的次方
C++
class Solution {
public:
bool isPowerOfThree(int n) {
if ( !n ) return false ;
while ( n != 1 ) {
if ( n % 3 ) return false ;
else n = n / 3 ;
}
return true ;
}
};
python
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0 :
return False
while n != 1 :
if ( n % 3 != 0 ) : return False
else : n = n / 3 ;
return True