# Problem 190: Reverse Bits

> <https://leetcode.com/problems/reverse-bits/?tab=Description>

## 思路

* 这道题的思路就是首先保留原先的 bit，同时 reverse bit 的顺序
* 保留原先 bit ： `n & 1`，这样 0 还是 0 ，1 还是 1
* 然后用 shift 的形式连接 bit，原来是从右向左，现在一连接就相当于 “reverse” 了 bits

```java
public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int rst = 0;
        for (int i = 0; i < 32; i++) {
            rst += (n & 1);
            n >>>= 1;
            if (i < 31) rst <<= 1;
        }

        return rst;
    }
}
```

## Follow Up

> If this function is called many times, how would you optimize it?

* 这个回答不错。 <https://discuss.leetcode.com/topic/9764/java-solution-and-optimization>


---

# 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://liuyang89116.gitbook.io/my-leetcode-book/post_chapter_2_math/bit-manipulation/problem-190-reverse-bits.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.
