给定一个整数,编写一个函数来判断它是否是 2 的幂次方。
示例 1:
输入: 1 输出: true 解释: 20 = 1
示例 2:
输入: 16 输出: true 解释: 24 = 16
示例 3:
输入: 218 输出: false
方法一
#include <stdio.h>
#include <stdbool.h>
bool isPowerOfTwo(int n){
if (n == 0) {
return false;
}
while (n % 2 == 0) {
n /= 2;
}
if (n == 1) {
return true;
}
return false;
}
int main()
{
printf("%d\n", isPowerOfTwo(4));
printf("%d\n", isPowerOfTwo(8));
printf("%d\n", isPowerOfTwo(12));
printf("%d\n", isPowerOfTwo(3));
return 0;
}
方法二
#include <stdio.h>
#include <stdbool.h>
//化为二进制,并进行按位与操作
bool isPowerOfTwo(int n){
if (n <= 0) {
return false;
} else if (n == 1) {
return true;
} else {
if ((n&(n-1)) == 0) {
return true;
} else {
return false;
}
}
}
int main()
{
printf("%d\n", isPowerOfTwo(4));
printf("%d\n", isPowerOfTwo(8));
printf("%d\n", isPowerOfTwo(12));
printf("%d\n", isPowerOfTwo(3));
return 0;
}