# Reverse Binary

```cpp
/**
* Reverse the binary bits of a given integer.
*/

/*
The idea:
 - msb effectively counts the number of bits in a number, since the remaining zero
   the come before the number are basically redundent.
 - the way we do this is by bit shifting the number to the right by 1, everytime
   and the moment the number is zero, means that we have reached the end, (there
   are no more bits to check that are remaining)
 - We add one to msb since when we do (1 << num_digits_2) - 1, that -1 gets rid
   of one bit.
 - all_ones bit shifts 1 to the right to the msb. -1 gets the previous numbers, which
   will always be all ones.

   Ex.
      .         <- msb
   000111010101
   001000000000 <- 1 << num_digits
   000111111111 <- (1 << num_digits - 1)
   000000101010 <- toggle with ^
*/

// actually runs in constant time, O(32)
unsigned msb(int num) 
{
    unsigned count = 0;
    while (num >>= 1)
        count++;
    return count;
}

int rev_binary(int num)
{
    int num_digits_2 = msb(num) + 1;
    int all_ones = (1 << num_digits_2) - 1;
    return num ^ all_ones;
}


/**
* Count the number of bits in a given integer.
* - see msb
*/


int main()
{
    int rev_n = rev_binary(483); 
    cout << rev_n << endl; // 28
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/bit-manipulation/reverse-binary.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
