2.4 KiB
Leetcode Reverse-Bits
2022-07-22 15:15
Algorithms:
#algorithm #bit_manipulation
Data structures:
#DS #bitset
Difficulty:
#coding_problem #difficulty_easy
Additional tags:
#leetcode
Revisions:
N/A
Related topics:
Links:
Problem
Reverse bits of a given 32 bits unsigned integer.
Examples
Example 1:
Input: n = 00000010100101000001111010011100 Output: 964176192 (00111001011110000010100101000000) Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
Input: n = 11111111111111111111111111111101 Output: 3221225471 (10111111111111111111111111111111) Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
Constraints
- The input must be a binary string of length
32
Thoughts
[!summary] This is a #bit_manipulation problem.
There are two methods:
- swapping bits inside the bitset
- shifting
Method 1: Swapping
This is the most simple and intuitive one, all you have to do is swap the first and last numbers, and continue like that.
Method 2: Shifting
The bitset has operations like this <<
>>
, which can be used to shift, and reverse the array.
The operation is already documented in the link above: Leetcode Reverse-Bits#Links
Solution
Method 1:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
// swap bits inside the function
bitset<32> nb(n);
bool tmp;
int l = 0, r = 31;
while (l < r) {
tmp = nb[l];
nb[l] = nb[r];
nb[r] = tmp;
l++;
r--;
}
return nb.to_ulong();
}
};
Shifting:
==#TODO solve it using shifting==