标签:ios bit return 位运算 作用 stream ++ for 树状
(1) 求n的第k位数字:n >> k & 1
(2) 返回n的最后一位1:lowbit(n) =n & -n
具体实现:
#include<iostream>
using namespace std;
int main()
{
int n=10;
for(int k=3; k>=0; K--) cout << (n >>i & 1) << endl;
return 0;
}
(1) x = 1010 lowbit(x) = 10
(2) x = 101000 lowbit(x) = 1000
x & -x = x & (~x + 1)
-x = ~x + 1
x = 1010 ....10000
~x = 0101 ....01111
~x + 1 = 0101 ....10000
x & (~x + 1) = 0000 ....10000
具体实现:
#include <iostream>
using namespace std;
int lowbit(int x)
{
return x & -x;
}
int main()
{
int n;
cin >> n;
while (n--)
{
int x;
cin >> x;
int res = 0;
while(x) x -= lowbit(x), res++;//每次减去x的最后一位1
cout << res <<endl;
}
return 0;
}
标签:ios bit return 位运算 作用 stream ++ for 树状
原文地址:https://www.cnblogs.com/lastk/p/12896553.html