Two method of making that:
1. As we know this is 32 bit integer. We just get the bit and shift to 31 - i.
1 class Solution { 2 public: 3 uint32_t reverseBits(uint32_t n) { 4 uint32_t result; 5 for (int i = 0; i < 32; i++) { 6 result |= ((n >> i) & 1) << (31 - i); 7 } 8 return result; 9 } 10 };
2. Swap bits
1 class Solution { 2 public: 3 uint32_t swapBits(uint32_t n, int i, int j) { 4 int first = (n >> i) & 1, second = (n >> j) & 1; 5 if (first ^ second) { 6 n ^= (1U << i) | (1U << j); 7 } 8 return n; 9 } 10 uint32_t reverseBits(uint32_t n) { 11 for (int i = 0; i < 16; i++) { 12 n = swapBits(n, i, 31-i); 13 } 14 return n; 15 } 16 };
LeetCode - Refresh - Reverse Bits
原文:http://www.cnblogs.com/shuashuashua/p/4358819.html