您的位置:首页 > 其它

“玲珑杯”ACM比赛 Round #5 I -- I am Two【位运算判断2的幂】

2016-11-27 01:42 363 查看
I -- I am Two

Time Limit:1s Memory Limit:64MByte

Submissions:521Solved:204

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

SOLUTION

玲珑杯”ACM比赛 Round #5

原题链接:http://www.ifrog.cc/acm/problem/1057
水题,判断一个数是否是2的幂,运用位运算,一行代码就可以搞定了。
代码:x&(x-1)==0?“Yes”?“No”。
原理:
这就要考虑一下二进制了,因为2的幂的二进制的最高为1,其余位均为0,而比它小1得到数的二进制的刚好相反,位数比它的少一位,但是全为1,这样按位与一下就可以了。
eg:8--->1000,7--->0111。

AC代码:
/**
* 行有余力,则来刷题!
* 博客链接:http://blog.csdn.net/hurmishine
*
*/
#include <iostream>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int n;
cin>>n;
if(n>0&&(n&(n-1))==0)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息