326. Power of Three

326. Power of Three

Question

Given an integer n, return true if it is a power of three. Otherwise, return false.

An integer n is a power of three, if there exists an integer x such that n == 3<sup>x</sup>.

Solution

与isPowerOfFour相同,如果n小于0则返回false。
如果n等于1则返回true。
递归,如果n可以整除3,则返回isPowerOfThree(n / 3)。
否则返回false。

Code

1
2
3
4
5
6
7
8
class Solution {
public boolean isPowerOfThree(int n) {
if(n <= 0) return false;
if(n == 1) return true;
if(n % 3 == 0) return isPowerOfThree(n / 3);
else return false;
}
}
Author

Xander

Posted on

2022-08-23

Updated on

2022-08-23

Licensed under

Comments