Power of Two
Given an integer, write a function to determine if it is a power of two.
One:
简单的利用while循环
判断输入的n在整除最多的2后是否为1;
#include<iostream>
using namespace std;
bool isPowerOfTwo(int n) {
while( (n % 2) == 0 && n >= 2)
n = n / 2;
if( n == 1)
return 1;
else
return 0;
}
int main (){
int n;
bool a;
cin >> n;
a = isPowerOfTwo(n);
cout << a;
}
Two:
通过观察发现:
2-1;4-10;8-100;16-1000;32-10000;64-100000......All power of two 的2进制都是只有最前边一位为1,其他位为0;
这些数n与n-1进行位运算&都是0;
(例如:32-10000 , 31-1111;
10000
& 01111
=00000)
所以有
#include<iostream>
using namespace std;
bool isPowerOfTwo(int n) {
if( n > 0 &&(n & (n-1)) == 0)
return 1;
else
return 0;
}
int main (){
int n;
bool a;
cin >> n;
a = isPowerOfTwo(n);
cout << a;
}
位运算:
#include<iostream>
using namespace std;
int main (){
int n,m;
cin >> n;
cin >> m;
cout << ( n & m );
}
Input: n = 8(100); m = 10(110);
Output: 8(100);