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 as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
思路一:
这题目一看就知道肯定要用位运算,但是要考虑到如果最高位是1的话,再右移位运算的时候左边会补1,所以要单独处理一下。
1 public int reverseBits(int n) { 2 int ret = 0; 3 int factor = 1; 4 factor = factor << 30; 5 int tmp = 2; 6 //处理最高位 7 if ((factor<<1 & n) != 0) { 8 ret += 1; 9 } 10 for(int i=0; i<31; i++) { 11 if ((factor & n) != 0) { 12 ret += tmp; 13 } 14 tmp = tmp << 1; 15 factor = factor >> 1; 16 } 17 return ret; 18 }
思路二:
把位运算运用到极致的方法。用(n >> i) & 1实现取位,用或运算实现加和。
1 public int reverseBits2(int n) { 2 int ret = 0; 3 for(int i=0; i<32; i++) { 4 int bit = (n >> i) & 1; 5 ret |= bit << (31 - i); 6 } 7 return ret; 8 }