190. Reverse Bits

2018-07-16  本文已影响0人  bin_guo

Leetcode: 190. Reverse Bits
Reverse bits of a given 32 bits unsigned integer.

Example:

Input: 43261596
Output: 964176192
Explanation: 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?

Hints:
  1. & Operator:
    only 1 and 1 can be 1, others will be 0, like 01001 & 00001 = 00001
  2. | Operator:
    only 0 and 0 can be 0, others will be 1, like 01001 | 00001 = 01001
  3. ~ Operator:
    for example, 8 = 00010000
    -8 = ~8 + 1 = 11101111 + 00000001 = 11110000
    ~8 = 11101111 = 00010000 - 00000001 = 00010001 = |-9| = -9
  4. ^ Operater:
    only 1 and 0, or 0 and 1 can be 1, others will be 0, like 01001 & 00001 = 01000
  5. << Operater:
    move all to left, and append 0s at the end, like 01001 << 1 = 010010
  6. >> Operater:
    move all to right, cut the last one, and append 0s at the start, like 01001 >> 2 = 00010
    the sign doesn't move
  7. <<< Operater:
    same to << Operater
  8. >>> Operater:
    same to >> Operater, but the sign moves
Solution:
public int reverseBits(int n) {
        int sum = 0;
        for (int i = 31; i >= 0; i--) {
            sum |= ((n & 1) << i); //use m as result, add the last bit to the (bits.length - i)th 
            n = n >>> 1; //move to next bit
        }
        return sum;
    }
上一篇下一篇

猜你喜欢

热点阅读