-
Notifications
You must be signed in to change notification settings - Fork 0
/
2的幂次方表示
53 lines (44 loc) · 1.47 KB
/
2的幂次方表示
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
http://cxsjsxmooc.openjudge.cn/2019t2summer2/002/
ANS:
该题需要明白二进制的运算方法 (不断除以2? 再对相关指数不断除以2再次进行分解?)
https://baike.baidu.com/item/%E4%BA%8C%E8%BF%9B%E5%88%B6%E6%95%B0/108101?fr=aladdin
余数为1该位的数就为1, 并且从最低位往最高位添数
#include <iostream>
using namespace std;
int pos[32];
//8758
inline int GetBit(int n,int i)
{
return (n >> i ) & 1; //位运算符, e.g. 137 //右移一位相当于除以2
//搞清楚对于一个int数右移一位的结果是什么
}
void Print(int n) {
bool first = true;
for(int i = 15; i >= 0; --i) {//最大限制为15bit //算每个bit上是不是为1
if( GetBit(n,i)) { //e.g. get the bit on the 15th position
//If this bit is 1, run the operation
if(! first ) {
cout << "+" ;
}
else
first = false; // Label --> Is this the first term?
if( i == 0)//i = 0 ==> if the bit is the last bit
cout <<"2(0)" ;
else if( i == 1) // i = 1 ==> if the bit the the second last bit
cout << "2";
else {
cout << "2(";
Print(i);//recursive decomposition //decomposition the index value
cout << ")";
}
}
}
return;
}
int main()
{
int n;
cin >> n;
Print(n);
return 0;
}