Monday, July 25, 2016

326. Power of Three

I think for the interview, the recursive version is good enough. Don’t forget that n == 1 is a valid case.

1:  class Solution {  
2:  public:  
3:    bool isPowerOfThree(int n) {  
4:      return n > 0 && (n == 1 || (n % 3 == 0 && isPowerOfThree(n / 3)));  
5:    }  
6:  };  

Anyway, there is a mathematical version.

1:  class Solution {  
2:  public:  
3:    bool isPowerOfThree(int n) {  
4:      int maxThrees = (int) pow(3, (int)(log(0x7FFFFFFF)/log(3)));  
5:      return n > 0 && maxThrees % n == 0;  
6:    }  
7:  };  

No comments:

Post a Comment