mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 190. Reverse Bits.md
This commit is contained in:
parent
7c1d137b9c
commit
7cd57aa4b1
21
190. Reverse Bits.md
Normal file
21
190. Reverse Bits.md
Normal 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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user