leetcode - 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
1 class Solution { 2 public: 3 uint32_t reverseBits(uint32_t n) { 4 int bits[32]; 5 for(int i=0; i<32; i++) 6 bits[i]=0; 7 int j = 0; 8 uint32_t sum = 0; 9 while(n!=0){ 10 int tp = n%2; 11 n /= 2; 12 bits[j] = tp; 13 j++; 14 } 15 for(int i=31, k=0; i>=0; i--, k++){ 16 sum += pow(2,k)*bits[i]; 17 } 18 return sum; 19 } 20 };
题目不难,但是如何optimize? 显然应该是用位操作。自己的这个方法太业余了。
http://www.bubuko.com/infodetail-670143.html 这个文章里讲了非常好的方法,一个是位操作,每次移位直接保存,然后输出即可。
当然,位操作必须要熟悉,与1相与得最后一位,与1(0)相或,将某一位设置为1(0); 每次都对最后一位操作,操作完之后左右移位,直到32位全部操作完。
example:
1 class Solution { 2 public: 3 uint32_t reverseBits(uint32_t n) { 4 uint32_t answer; 5 uint32_t int i; 6 7 answer = 0; 8 9 /*把一个unsigned int 数字1一直左移,直到它变成全0的时候,也就得到了该机器内unsigned int的长度*/ 10 for (i = 1; i != 0; i <<= 1) 11 { 12 answer <<= 1; 13 if (value & 1) { answer |= 1; } 14 value >>= 1; 15 } 16 17 return answer; 18 } 19 };
然而更好的办法是一种二分翻转的办法 (自己起的名字。。。)
http://graphics.stanford.edu/~seander/bithacks.html
在斯坦福的这篇文章里面介绍了众多有关位操作的奇思妙想,有些方法的确让人称赞,其中对于位翻转有这样的一种方法,将数字的位按照整块整块的翻转,例如32位分成两块16位的数字,16位分成两个8位进行翻转,这样以此类推知道只有一位。
对于一个8位数字abcdefgh来讲,处理的过程如下
abcdefgh -> efghabcd -> ghefcdab -> hgfedcba
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; } };
这种方法的效率为O(log sizeof(int))。
from: http://www.bubuko.com/infodetail-670143.html
amazing!