位运算概况
n的二进制表示中第k位是0还是1
n = 15 = (1111)
①先把第k位移到最后一位 n >> k;
②与1进行与运算 n&1
这样就可以知道 n二进制位 第k位是几
lowbit(x)
lowbit(x) 是返回最后以为1是多少
eg:
x = (1010) ; lowbit(x) == (10)
x = (101000) ; lowbit(x) == (1000)
代码
int lowbit (int x)
{
return x & -x;
}
例题
求n二进制数中,有几个1
#include <iostream>
using namespace std;
int lowbit (int x)
{
return x & -x;
}
int main()
{
int n;
cin >> n;
int res = 0;
while (n) n -= lowbit(n), res ++;
cout << res << ' ';
system("pause");
}