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).
题目标签: Bit Manipulation
这道题目让我们把n的bits都反转一下。我们可以通过 & 1 判断最右边一位是 0 还是 1。然后利用 >> 把n的bits向右边移动一位;利用 << 把res的位数向左边移动一位,注意res的最后一次是不需要移动的。
Java Solution:
Runtime beats 42.91%
完成日期:06/25/2017
关键词:Bit Manipulation
关键点:&, >>, << 的运用
public class Solution
{
// you need treat n as an unsigned value
public int reverseBits(int n)
{
int res = 0; for(int i=0; i<32; i++)
{ if((n & 1) == 1) // meaning the right most bit is 1
res += 1; n = n >> 1; if(i != 31)
res = res << 1; } return res;
}
}
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List