LeetCode/190. Reverse Bits.md
2018-10-23 00:00:03 +08:00

22 lines
839 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [190. Reverse Bits](https://leetcode.com/problems/reverse-bits/description/)
# 思路
将给定的数的二进制进行翻转。
定义res为32位无符号型且初始值为0可从低位到高位依次取得给定的数的32位bit值再用或运算赋值给res的最低位res不断左移。
可将给定的数与一个mask进行与操作取得特定位数上的值mask只有一位是1。可通过对mask移位(如下代码)或者对给定的数移位来达到取特定位的目的。
# C++
```
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
uint32_t mask = 1;
for (uint32_t i = 0; i < 32; ++i) {
// n & mask取得第i位
res = (res << 1) | ((n & mask) >> i);
mask = mask << 1;
}
return res;
}
};
```