“玲珑杯”ACM比赛 Round #5
I am Two
Time Limit:1s Memory Limit:64MByte
Submissions:423Solved:166
DESCRIPTION
Check whether an integer n is a power of 2.
INPUT
First line contains a single integer T (T<=20) which denotes the number of test cases.
For each test case, there is an 32-bit integer N .
OUTPUT
For each case, output the "Yes" or "No" in a single line.
SAMPLE INPUT
3
1
3
8
SAMPLE OUTPUT
Yes
No
I am Two
Time Limit:1s Memory Limit:64MByte
Submissions:423Solved:166
DESCRIPTION
Check whether an integer n is a power of 2.
INPUT
First line contains a single integer T (T<=20) which denotes the number of test cases.
For each test case, there is an 32-bit integer N .
OUTPUT
For each case, output the "Yes" or "No" in a single line.
SAMPLE INPUT
3
1
3
8
SAMPLE OUTPUT
Yes
No
Yes
题解:这道题的意思就是判断一个数是否是2的n次幂,如果是就输出Yes,否则输出No.
可以用“按为与运算”来解决这道题,将给出的那个数和那个数-1的二进制进行与运算,如果结果为0,那这个数就是2的n次幂。因为2的n次幂有一个特点,都是10、100、1000、10000、、、这种格式,而2的n次幂-1的二进制则是01、011、0111、01111、、、与运算正好为0.
#include <stdio.h>
bool fun(int m)
{
bool scnt=0;
if((m>0)&&(m&(m-1))==0)
scnt=1;
return scnt;
}
int main()
{
int n;
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
if(fun(n))
printf("Yes\n");
else
printf("No\n");
}
return 0;
}