Create 190. Reverse Bits.md

This commit is contained in:
唐树森 2018-10-23 00:00:03 +08:00 committed by GitHub
parent 7c1d137b9c
commit 7cd57aa4b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

21
190. Reverse Bits.md Normal file
View File

@ -0,0 +1,21 @@
# [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;
}
};
```