### Reverse Bits

Total Accepted: 43722 Total Submissions: 150010 Difficulty: Easy

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

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

Related problem: Reverse Integer

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

1.假设只有8位，n=0000 1101，要转化成ret=10110000

2.首先ret=00000000

3.判断n的最后一位是0还是1，int b=n&1，n>>=1；

4.ret = ret | b，最后一位放到ret的最后一位，ret<<=1；

5.if(i--<8)转3；（这里i初值为8）；

code：

class Solution {
public:
uint32_t reverseBits(uint32_t n) {
int ret=0;
int i=32;
while(i--)
{
ret<<=1;// 这里ret先移位，再赋值，因为当n取得最高位的时候，ret不需要再移位
ret |= n&1;
n>>=1;
}
return ret;
}
};

#### 190. Reverse Bits [easy] (Python)

2016-06-18 11:04:11

#### LeetCode(190) Reverse Bits

2015-03-22 12:46:11

#### 【LeetCode-面试算法经典-Java实现】【190-Reverse Bits（反转二制）】

2015-08-24 07:15:15

#### 【LeetCode-190】 Reverse Bits(C++)

2016-05-20 23:11:28

#### 【LeetCode】Reverse Bits 翻转二进制

2015-04-23 14:59:36

#### Leetcode_190_Reverse Bits

2015-07-13 21:33:35

#### LeetCode 190. Reverse Bits 题解

2017-03-02 11:09:44

#### LEETCODE 190

2016-03-11 19:36:13

#### LeetCode 第 190 题 (Reverse Bits)

2016-04-18 21:31:15

#### 【LeetCode】【Python题解】Reverse Integer

2014-07-20 20:06:48

## 不良信息举报

LeetCode:Reverse Bits