#include <stdio.h>
#include <math.h>
int main(){
int num,i;
scanf("%d",&num);
int a[num];
for (i=0; i<num; i++){
scanf("%d",&a[i]);
}
for (i=0; i<num+1; i++){
if (pow(2,i) == a[i]){
printf("%d\n",a[i]);
}
}
}
我正在尝试创建一个程序,显示数组中的整数(如果它是 2 的幂)。前任;数组包含整数 (1,2,4,9),它将仅打印 1,2 和 4。
这段代码有什么问题?它适用于某些测试用例,但不适用于大多数测试用例。
最佳答案
如果值
是2的幂,则仅设置一位:
#include <stdbool.h>
#include <limits.h>
bool is_pow_of_2(unsigned value)
{
int count = 0;
for (unsigned shift = 0; shift < sizeof(value) * CHAR_BIT; ++shift) {
if (value & 1 << shift) // test if bit shift is set
++count;
if (count > 1) // if there a more than one bits set in value
return false; // it cannot be a power of 2
}
return true;
}
<小时/>
B计划:
bool is_pow_of_2(signed value)
{
if(value <= 0)
return false;
// ...
关于C 程序显示数组中的数字(如果是 2 的幂),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53258482/