You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# include <bits/stdc++.h>
using namespace std ;
int lowbit ( int x ) {
return x & ( - x ) ;
}
//输出十进制对应的二进制数(模板)
void print ( int n ) {
//输出8个数位的二进制数
for ( int i = 7 ; i > = 0 ; i - - )
printf ( " %d " , n > > i & 1 ) ;
printf ( " \n " ) ;
}
const int N = 12 ;
int sum [ N ] ;
int main ( ) {
int x = 28 ; //二进制 00011100;
cout < < " 初始数字: " < < x < < endl ;
cout < < " 二进制表示: " ;
print ( x ) ;
cout < < " 仅有末位1: " < < lowbit ( x ) < < endl ;
cout < < " 去掉末位1: " < < ( x & ~ lowbit ( x ) ) < < endl ;
//前缀和的lowbit加速技巧
for ( int i = 0 ; i < 4 ; i + + ) sum [ 1 < < i ] = 1 ; //按数位压缩方式存入前缀和数组[前缀和数组下标从1开始]
cout < < " 实际的存储情况: " < < endl ;
for ( int i = 0 ; i < 9 ; i + + ) cout < < i < < " " < < sum [ i ] < < endl ;
//这里补充一下~这个逻辑运算符,它的作用是把一个二进制数每一位取反 即每一位的0变成1,1变成0
//所以i&~lowbit(i)的意义为去掉一个二进制数的lowbit后的值
for ( int i = 1 ; i < ( 1 < < 4 ) ; i + + ) {
sum [ i ] = sum [ i & ~ lowbit ( i ) ] + sum [ lowbit ( i ) ] ;
cout < < " i= " < < i < < " sum[i]= " < < sum [ i ] < < endl ;
}
//每次去掉最后一个1
for ( int j = x ; j ; j - = lowbit ( j ) ) //枚举可能的上一次状态
cout < < j < < endl ;
return 0 ;
}