LeetCode 190. Reverse Bits (反转位)
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
关键点:&, >>, << 的运用
1 public class Solution 2 { 3 // you need treat n as an unsigned value 4 public int reverseBits(int n) 5 { 6 int res = 0; 7 8 for(int i=0; i<32; i++) 9 { 10 11 if((n & 1) == 1) // meaning the right most bit is 1 12 res += 1; 13 14 n = n >> 1; 15 16 if(i != 31) 17 res = res << 1; 18 19 } 20 21 return res; 22 } 23 }
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List