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?


思路:

该题是一道与二进制位运算有关的题目。首先将给定数字n的第一位的数字取出将其向左移动31位。再取第二位数字,向左移动30位,依次类推。


代码:

public int reverseBits(int n) {
        int result = 0;
        for(int i=0;i<32;i++){
            result |= ((n>>i)&1) << (31-i);
        }
        return result;
}

你可能感兴趣的:(Leetcode 190 - Reverse Bits)