LeetCode/solutions/190. Reverse Bits.md

49 lines
1.8 KiB
Markdown
Raw Normal View History

2018-10-22 16:00:03 +00:00
# [190. Reverse Bits](https://leetcode.com/problems/reverse-bits/description/)
# 思路
2018-10-23 09:53:13 +00:00
将给定的数的二进制进行翻转。
## 思路一、常规思路
2018-10-22 16:00:03 +00:00
定义res为32位无符号型且初始值为0可从低位到高位依次取得给定的数的32位bit值再用或运算赋值给res的最低位res不断左移。
2018-10-23 09:53:13 +00:00
可将给定的数与一个mask进行与操作取得特定位数上的值mask只有一位是1。可通过对mask移位(如下代码)或者对给定的数移位来达到取特定位的目的。
## 思路二、巧妙思路
* 1、若只有两位: ab, 则将第一位右移一位、将第二位左移一位即可得到ba;
* 2、若只有四位: abcd, 则先将前两位右移两位、后两位左移两位再分别对两个两位进行情况1的操作即可得到dcba;
* 3、若只有八位: abcdefgh, 则先将前四位右移四位、后四位左移四位再依次进行情况1、2的操作即可得到hgfedcba;
* ......
则针对此题的具体步骤是:
* 将前16位右移16位将后16位左移16位;
* 将0-7、16-23位右移八位将8-15、24-31位左移八位(最低位为31位);
* ......
2018-10-22 16:00:03 +00:00
# C++
2018-10-23 09:53:13 +00:00
## 思路一
2018-10-22 16:00:03 +00:00
```
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;
}
};
```
2018-10-23 09:53:13 +00:00
## 思路二
```
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
n = (n >> 16) | (n << 16);
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
return n;
}
};
```