forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_bits.cpp
More file actions
50 lines (46 loc) · 837 Bytes
/
reverse_bits.cpp
File metadata and controls
50 lines (46 loc) · 837 Bytes
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
#include <string>
#include <iostream>
#include <vector>
#include <inttypes.h>
using namespace std;
void print(uint32_t n)
{
for (int i=0; i<32; i++)
{
if ((n & 0x80000000) != 0)
{
cout << "1";
}
else
{
cout << "0";
}
n = n << 1;
}
}
/**
* 移位注意事项:无符号数>>操作左边插入0,有符号数左边插入不确定
* 比较简单
*/
uint32_t reverseBits(uint32_t n)
{
uint32_t result = 0;
for (int i=0; i<32; i++)
{
if ((n & 0x80000000) != 0)
{
result = result | 0x80000000;
}
if (i != 31)
{
result = result >> 1;
n = n << 1;
}
}
return result;
}
int main()
{
cout << reverseBits(43261596) << endl;
return 1;
}