342. Power of Four

342. Power of Four

Question

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

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

Solution

递归,如果n小于等于零则返回false。
如果n等于1则返回true。

如果n可以除以4,则递归返回n/4。

Code

1
2
3
4
5
6
7
8
9
class Solution {
public boolean isPowerOfFour(int n) {
if(n <= 0) return false;
if(n == 1) return true;

if(n % 4 == 0) return isPowerOfFour(n / 4);
else return false;
}
}
Author

Xander

Posted on

2022-08-22

Updated on

2022-08-22

Licensed under

Comments