# Leetcode Reverse-Bits

#### 2022-07-22 15:15

> ##### Algorithms:
>
> #algorithm #bit_manipulation
>
> ##### Data structures:
>
> #DS #bitset
>
> ##### Difficulty:
>
> #coding_problems #difficulty_easy
>
> ##### Additional tags:
>
> #leetcode
>
> ##### Revisions:
>
> N/A

##### Related topics:

##### Links:

- [Link to problem](https://leetcode.com/problems/reverse-bits/)
- [Solution and detailed explanation](<https://leetcode.com/problems/reverse-bits/discuss/1232842/JAVA-C%2B%2B-%3A-0ms-or-O(1)-Time-Complexity-or-in-place-or-Detailed-Explanation>)
- [Shifting solution an explanation](<https://leetcode.com/problems/reverse-bits/discuss/54741/O(1)-bit-operation-C++-solution-(8ms)/301342>)

  ***

### 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

id:: 641ff3d4-afbc-4d0e-82d5-8adb2ff0ad93

> [!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. ((641ff3d4-afbc-4d0e-82d5-8adb2ff0ad93))

### Solution

#### Method 1:

```cpp
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==
