forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
190_Reverse_Bits
72 lines (62 loc) · 1.67 KB
/
190_Reverse_Bits
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
Leetcode 190: Reverse Bits
Detailed Video Explanation: https://youtu.be/ZW7st_pN05w
C++:
====
Method 1:
---------
uint32_t reverseBits(uint32_t n) {
uint32_t result = 0;
for(int i = 0; i < 32; ++i){
result <<= 1;
if(n&1) result++;
n >>= 1;
}
return result;
}
Method 2:
--------
uint32_t reverseBits(uint32_t n) {
n = ((n & 0xffff0000) >> 16) | ((n & 0x0000ffff) << 16);
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
return n;
}
Java:
=====
Method 1:
---------
public int reverseBits(int n) {
int result = 0;
for(int i = 0; i < 32; ++i){
result <<= 1;
if ((n&1) > 0) result++;
n >>= 1;
}
return result;
Method 2:
--------
public int reverseBits(int n) {
return Integer.reverse(n);
}
Python3:
========
Method 1:
--------
def reverseBits(self, n: int) -> int:
result = 0
for i in range(32):
result <<= 1
if n&1: result += 1
n >>= 1
return result
Method 2:
--------
def reverseBits(self, n: int) -> int:
n = ((n & 0xffff0000) >> 16) | ((n & 0x0000ffff) << 16)
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8)
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4)
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2)
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1)
return n