位运算
主要内容
low_bit
返回的是一个整数的二进制形式最右边的“1”,比如对于(101011000)2
返回的是(1000)2
1 2 3
| int low_bit(int n){ return n&-n; }
|
例题
low_bit
二进制表示中1的个数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| #include<bits/stdc++.h> using namespace std;
int low_bit(int n){
return n&-n; }
void work(){ int n; cin>>n;
int cnt=0; while(n) cnt++,n-=low_bit(n); cout<<cnt<<endl; }
int main(){ work(); return 0; }
|