LeetCode 190. Reverse Bits

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

Related problem: Reverse Integer

分析:
最简单的做法,原数不断右移取出最低位,赋给新数的最低位后新数再不断左移。
时间 O(1) 空间 O(1)

[cc lang=”C++”]
public class Solution {
public int reverseBits(int n) {
int res = 0;
for(int i = 0; i < 32; i++, n >>= 1){
res = res << 1 | (n & 1); } return res; } } [/cc] 另一种代码写法: [cc lang="C++"] class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t result= 0; for(int i=0; i<32; i++) result = (result<<1) + (n>>i &1);

return result;
}
};
[/cc]

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据