题目:
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
链接: http://leetcode.com/problems/reverse-bits/
2/21/2017, Java
参考别人的算法
错误:
第7行百思不得其解,为什么res = res + (n >> i) & 1是错的,而res += (n >> i) & 1是对的。原因是+/-的优先级居然比位运算要高!
1 public class Solution { 2 // you need treat n as an unsigned value 3 public int reverseBits(int n) { 4 int res = 0; 5 for (int i = 0; i < 32; i++) { 6 res = res << 1; 7 res += (n >> i) & 1; 8 } 9 return res; 10 } 11 }
据说还有其他算法:
Bit Twiddling Hacks以及Hacker's Delight
准备留给二刷