leetCode #190 reverse bits
2015-03-08 15:59
344 查看
题目:将十进制数进行二进制反转后输出新的十进制数
分析:可以先转进制,反转,再转回来;但是其实了解了位操作之后就不需要如此麻烦的转化了。因为本身计算机存储的就是二进制,也支持二进制的位操作。
答案:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
for (int i = 0; i < 32; ++i) {
res = res << 1;
if (n & 1 == 1) {
res+= 1;
}
n = n >> 1;
}
return res;
}
};
更简洁的写法:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
for (int i = 0; i < 32; ++i) {
res |= (((n >> i) & 1) << (31 - i));
}
return res;
}
};
tips:位运算做的是最低位,且优先级不如+
分析:可以先转进制,反转,再转回来;但是其实了解了位操作之后就不需要如此麻烦的转化了。因为本身计算机存储的就是二进制,也支持二进制的位操作。
答案:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
for (int i = 0; i < 32; ++i) {
res = res << 1;
if (n & 1 == 1) {
res+= 1;
}
n = n >> 1;
}
return res;
}
};
更简洁的写法:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
for (int i = 0; i < 32; ++i) {
res |= (((n >> i) & 1) << (31 - i));
}
return res;
}
};
tips:位运算做的是最低位,且优先级不如+
相关文章推荐
- LeetCode #190 Reverse Bits
- Leetcode 190 Reverse Bits 位运算
- 【LeetCode】190 Reverse Bits
- LeetCode 190 Reverse Bits
- 【LEETCODE】190-Reverse Bits
- Leetcode190-Reverse Bits
- Leetcode 190 Reverse Bits
- LeetCode 190 :Reverse Bits
- Leetcode-190 Reverse Bits 数字二进制倒置
- leetcode 190 Reverse Bits
- [leetcode 190]Reverse Bits
- leetcode-190 Reverse Bits
- leetcode:190 Reverse Bits-每日编程第三十二题
- LeetCode(190) Reverse Bits
- LeetCode#190 Reverse Bits
- LeetCode(190) Reverse Bits
- leetcode 190 Reverse Bits
- Leetcode 190 Reverse Bits
- 【LeetCode-190】 Reverse Bits(C++)
- LeetCode 190: Reverse Bits