Monday, August 7, 2017

[Leetcode] Power of Three, Solution

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?

[Thoughts]
不断的用3来除,如果余数不为0,则判否。


[Code]
1:    bool isPowerOfThree(int n) {  
2:      if(n == 0) return false;  
3:        
4:      if(n == 1) return true;  
5:        
6:      return (n%3 ==0) && isPowerOfThree(n/3);  
7:    }  

followup的问题,如果不用loop或recursion的话,一般都是指数学方法来处理,这里就不花时间了。

No comments: