[LeetCode] #190 Reverse Bits

#190 Reverse Bits

Question

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

Thinking

此題是考位元運算,關鍵在於要知道「>>」與「<<」的用法,前者表示將所有位元向右位移;後者表示向左位移,舉個例子

  • 5 >> 1:00101所有位元向右位移1位,即00010
  • 5 << 1:00101所有位元向左位移1位,即01010

My C# Solution

public class Solution {
    public uint reverseBits(uint n) {
        uint result = 0;
        for(var i = 0; i < 32; i++)
        {
            result = (result << 1) + (n & 1);
            n = n >> 1;
        }
        return result;
    }
}