[LeetCode] Power of Four

342. Power of Four

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 == 4x.

1
2
3
4
5
6
7
8
9
10
class Solution {
//4^0 + 4^1 + 4^2 .... + 4^15
const int bit = 1431655765;
public:
bool isPowerOfFour(int n) {
if(n <= 0) return false;
bitset<32> bi(n);
return (bit & n) == n and bi.count() == 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/power-of-four/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.