lowbit(i)=-i&i=2^p 从最低位1开始截取(截取一个1及其后面的0) 组成的数转换为10进制 去年蓝桥的填空题就被坑了
#include<iostream>
#include<string>
using namespace std;
int a[1000000];
int index;
void toBinary(int n){
index=0;
while(n){
a[index++]=n%2;
n/=2;
}
for(int i=index-1;i>=0;i--){
cout<<a[i];
}
}
int main(){
freopen("output.txt","w",stdout);
int n;
cin>>n;
for(int i=0;i<=n;i++ ){
cout<<i<<":";
toBinary(i);
cout<<"\t-"<<i<<"&"<<i<<":"<<(-i&i)<<endl;
}
return 0;
}
输入100后的运行结果:
0: -0&0:0
1:1 -1&1:1
2:10 -2&2:2
3:11 -3&3:1
4:100 -4&4:4
5:101 -5&5:1
6:110 -6&6:2
7:111 -7&7:1
8:1000 -8&8:8
9:1001 -9&9:1
10:1010 -10&10:2
11:1011 -11&11:1
12:1100 -12&12:4
13:1101 -13&13:1
14:1110 -14&14:2
15:1111 -15&15:1
16:10000 -16&16:16
17:10001 -17&17:1
18:10010 -18&18:2
19:10011 -19&19:1
20:10100 -20&20:4
21:10101 -21&21:1
22:10110 -22&22:2
23:10111 -23&23:1
24:11000 -24&24:8
25:11001 -25&25:1
26:11010 -26&26:2
27:11011 -27&27:1
28:11100 -28&28:4
29:11101 -29&29:1
30:11110 -30&30:2
31:11111 -31&31:1
32:100000 -32&32:32
33:100001 -33&33:1
34:100010 -34&34:2
35:100011 -35&35:1
36:100100 -36&36:4
37:100101 -37&37:1
38:100110 -38&38:2
39:100111 -39&39:1
40:101000 -40&40:8
41:101001 -41&41:1
42:101010 -42&42:2
43:101011 -43&43:1
44:101100 -44&44:4
45:101101 -45&45:1
46:101110 -46&46:2
47:101111 -47&47:1
48:110000 -48&48:16
49:110001 -49&49:1
50:110010 -50&50:2
51:110011 -51&51:1
52:110100 -52&52:4
53:110101 -53&53:1
54:110110 -54&54:2
55:110111 -55&55:1
56:111000 -56&56:8
57:111001 -57&57:1
58:111010 -58&58:2
59:111011 -59&59:1
60:111100 -60&60:4
61:111101 -61&61:1
62:111110 -62&62:2
63:111111 -63&63:1
64:1000000 -64&64:64
65:1000001 -65&65:1
66:1000010 -66&66:2
67:1000011 -67&67:1
68:1000100 -68&68:4
69:1000101 -69&69:1
70:1000110 -70&70:2
71:1000111 -71&71:1
72:1001000 -72&72:8
73:1001001 -73&73:1
74:1001010 -74&74:2
75:1001011 -75&75:1
76:1001100 -76&76:4
77:1001101 -77&77:1
78:1001110 -78&78:2
79:1001111 -79&79:1
80:1010000 -80&80:16
81:1010001 -81&81:1
82:1010010 -82&82:2
83:1010011 -83&83:1
84:1010100 -84&84:4
85:1010101 -85&85:1
86:1010110 -86&86:2
87:1010111 -87&87:1
88:1011000 -88&88:8
89:1011001 -89&89:1
90:1011010 -90&90:2
91:1011011 -91&91:1
92:1011100 -92&92:4
93:1011101 -93&93:1
94:1011110 -94&94:2
95:1011111 -95&95:1
96:1100000 -96&96:32
97:1100001 -97&97:1
98:1100010 -98&98:2
99:1100011 -99&99:1
100:1100100 -100&100:4