342 - 4的幂
很久没逛过leetcode了,今天上去随机看了道题,试了试
342题,题目是: 检测一个数字,是否是4的整数幂,例如1=40,16=42
题是简单难度的。先看看4的幂都有哪些特点,把2进制的表示列出来:
0000 0001 = 1
0000 0100 = 4
0001 0000 = 16
可以发现,4的幂,二进制中只有1位是1,且这个1在偶数索引处(从低到高), 所以把参数转为二进制,然后判断1的个数,且1的索引是否为偶数即可。
#include <cstddef>
#include <iostream>
#include <limits>
using namespace std;
class Solution
{
public:
bool isPowerOfFour(int n)
{
if (n <= 0)
{
return false;
}
// 确认n的二进制表示中只有一个1
if ((n & (n - 1)) != 0)
{
return false;
}
bool bit_found = false;
auto bits = numeric_limits<int>::digits;
for (size_t i = 0; i < bits; i++)
{
// 从最低位开始判断,依次检查每个位是否为1
bool bit = (n >> i) & 1;
if (bit)
{
if (bit_found || i % 2 == 1)
{
return false;
}
else
{
bit_found = true;
}
}
}
return bit_found;
}
};