2016年2月11日 星期四

LEET code -- 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?


如果不用loop
class Solution(object):
    def isPowerOfThree(self, n):
        # 1162261467=3^19. 3^20 is bigger than int.
        return n > 0 and 1162261467 % n == 0



1
2
3
4
5
bool isPowerOfThree(int n) {
    if(n<=0)return false;
    while(n%3==0)n/=3;
    return n==1? true:false;
}

沒有留言:

張貼留言