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?
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?
Hide Tags: Bit Manipulation(位操作)
解题思路:
(1)将需要翻转的数n跟1进行“&”运算,取得最低位上的数,
(2)左移到对应位置上,实现翻转。
(3)将翻转的结果加入到result中
(4)将n>>1右移一位,继续遍历
代码如下:
public static int reverseBits(int n)
{
int result=0;
for (int i = 0; i < 32; i++)
{
//获取n对应的二进制数的最右边(最低位)上的数
int temp=n&1;
//左移到对应位置上,实现翻转
int reverseTemp=temp<<(31-i);
//将翻转的结果加入到result中
result=result|reverseTemp;
//进入次低位 >>>:表示无符号数的右移动
n=n>>>1;
}
return result;
}