-
Notifications
You must be signed in to change notification settings - Fork 2
/
ex2.cpp
80 lines (72 loc) · 1.36 KB
/
ex2.cpp
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include"stdfx.h"
/*将整数A转换为B */
int bitSwapRequired(int a, int b)
{
int cnt = 0;
for (int c = a^b; c != 0; c &= c - 1)
{
++cnt;
}
return cnt;
}
/*二进制中有多少个1*/
int countOnes(int num)
{
int cnt = 0;
for (; num; num &= num - 1)
{
++cnt;
}
return cnt;
}
/*
二进制表示
*/
string binaryRepresentation(string n)
{
int int_part = stoi(n.substr(0, n.find('.')));
double dec_part = stod(n.substr(n.find('.')));
string int_str = "";
string dec_str = "";
if (int_part == 0)
{
int_str.push_back('0');
}
while (int_part > 0)
{
int c = int_part % 2;
int_str.push_back('0' + c);
int_part = int_part >> 1;
}
reverse(int_str.begin(), int_str.end());
while (dec_part > 0.0)
{
if (dec_str.length() > 32)
{
return "ERROR";
}
double remain = dec_part * 2;
if (remain >= 1.0)
{
dec_str.push_back('1');
dec_part = remain - 1.0;
}
else{
dec_str.push_back('0');
dec_part = remain;
}
}
return dec_str.length() > 0 ? int_str + "." + dec_str : int_str;
}
/*??更新二进制位*/
int updateBits(int n, int m, int i, int j)
{
int right_part = n&((1 << i) - 1);
int left_part = j >= 31 ? 0 : (n >> (j + 1)) << (j + 1);
return left_part | (m << i) | right_part;
}
/*O(1)时间检测2的幂次*/
bool checkPowerOf2(int n)
{
return n > 0 && (n&(n - 1)) == 0;
}