> For the complete documentation index, see [llms.txt](https://soumyajit4419.gitbook.io/ds-algo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://soumyajit4419.gitbook.io/ds-algo/bits-manipulation-and-mathematics/reverse-bits.md).

# 1.Reverse Bits

```
Example 1:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000
```

```cpp
class Solution
{
public:
    uint32_t reverseBits(uint32_t n)
    {

        bitset<32> b(n);

        int start = 0;
        int end = 31;
        while (start <= end)
        {
            if (b[end] == 1 && b[start] == 0)
            {
                b.set(start, 1);
                b.set(end, 0);
            }
            else if (b[end] == 0 && b[start] == 1)
            {
                b.set(start, 0);
                b.set(end, 1);
            }

            start++;
            end--;
        }

        return b.to_ulong();
    }
};
```

**Time Complexity: O(n )**

## Reverse Bits when an integer is given and return an integer

```cpp
unsigned int revBits(unsigned int n)
{

    int rev = 0;
    while (n > 0)
    {
        // bitwise left shift
        // 'rev' by 1
        rev <<= 1;

        // if current bit is '1'
        if (n & 1 == 1)
        {
            rev = rev ^ 1;
        }

        // bitwise right shift
        // 'n' by 1
        n >>= 1;
    }
    return rev;
}
```
