Skip to content

Commit f3b485d

Browse files
committed
Solved problem 190 : Reverse Bits
1 parent 831b8dd commit f3b485d

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Problem: 190
3+
* Name: Reverse Bits
4+
* Difficulty: Easy
5+
* Topic: Bit Manipulation
6+
* Link: https://leetcode.com/problems/reverse-bits/
7+
*/
8+
9+
#include <bits/stdc++.h>
10+
using namespace std;
11+
12+
// Traverse the number
13+
// Time Complexity: O(32)
14+
// Space Complexity: O(1)
15+
uint32_t reverseBitsTraverse(uint32_t n) {
16+
uint32_t result = 0;
17+
for (int _ = 0; _ < 32; _++){
18+
result <<= 1;
19+
result |= n & 1;
20+
n >>= 1;
21+
}
22+
return result;
23+
}
24+
25+
// Specific for 32 bits
26+
// Time Complexity: O(5)
27+
// Space Complexity: O(1)
28+
uint32_t reverseBitsManipulation(uint32_t n) {
29+
// Switch the two halves of the 32 bits
30+
n = (n >> 16) | (n << 16);
31+
// Switch the 1st/2nd half of each quarter
32+
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);
33+
// Switch the 1st/2nd half of each eighth
34+
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
35+
// Switch the 1st/2nd half of each sixteenth
36+
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
37+
// Switch the 1st/2nd half of each thirty-second
38+
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
39+
return n;
40+
}

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
### Problems Solved
1818

19-
| Total | 38 |
19+
| Total | 39 |
2020
|:---:|:---:|
2121

2222
#### Search By Topic
@@ -27,7 +27,7 @@
2727
| Backtracking | 0 |
2828
| Binary Search | 2 |
2929
| Binary Trees | 8 |
30-
| Bit Manipulation | 5 |
30+
| Bit Manipulation | 6 |
3131
| Dynamic Programming 1D | 1 |
3232
| Dynamic Programming 2D | 0 |
3333
| Graphs | 1 |
@@ -46,7 +46,7 @@
4646

4747
| Difficulty | Number |
4848
|:---|---:|
49-
| Easy | 37 |
49+
| Easy | 38 |
5050
| Medium | 1 |
5151
| Hard | 0 |
5252

0 commit comments

Comments
 (0)