我们知道,任何一个正整数都可以被表示成一个二进制数。如:
[left ( 8 ight )_{10} = left ( 1000 ight )_{2}]
那么定义一个函数 [f=lowbit(x)]
代表x的二进制表达式中最低位的1所对应的值
比如:
( lowbit(left ( 8 ight )_{10})=lowbitleft ( left ( 1000 ight ) _{2} ight) = 8 )
( lowbit(left ( 6 ight )_{10})=lowbitleft ( left ( 110 ight ) _{2} ight) = 2 )
(f=lowbit(x)) = 2^k,(k是x化为二进制后最右边有几个连续的零)e.g :(lowbit(6)) = 2^1 = 2;
实现方式: lowbit(x)=x&(-x)
记录一个十进制数的二进制表达中有几个一:
1 #include <bits/stdc++.h> 2 using namespace std; 3 #define lowbit(x) x&(-x) 4 5 int main() 6 { 7 int x; 8 while(~scanf("%d",&x)){ 9 int cnt=0; 10 while(x){ 11 x-=lowbit(x); 12 cnt++; 13 } 14 printf("%d ",cnt); 15 } 16 return 0; 17 }
拓:(lowbit left ( x ight ) = max_{2^{k}|x}2^{k})
(nmid m )表示 n是m的约数