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?算法
反转一个32位无符号的整数。this
设这个数为k,用一个初值为0的数r保存反转后的结果,用1对k进行求与,其结果与r进行相加,再对k向右进行一位移位,对r向左进行一位移位。值到k的最后一位处理完。spa
算法实现类.net
public class Solution { public int reverseBits(int n) { int result = 0; for (int i = 0; i < 32; i++) { result += n & 1; n >>>= 1; if (i < 31) { result <<= 1; } } return result; } }