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?


递归或循环

递归和循环的做法很简单,就是不停的除以3,直到不能整除,结果是1的话,就是3的指数,否则则不是。
但是这个题目的follow up不让用循环和递归。

1
2
3
public boolean isPowerOfThree(int n) {
return n > 0 && (n == 1 || (n % 3 == 0 && isPowerOfThree(n / 3)));
}
1
2
3
4
5
public boolean isPowerOfThree(int n) {
if (n > 1)
while (n % 3 == 0) n /= 3;
return n == 1;
}

Math

Ref: https://discuss.leetcode.com/topic/33536/a-summary-of-all-solutions-new-method-included-at-15-30pm-jan-8th