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 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/
题解:
用了比较naive的方法, 最高位shift然后和1与,然后再加到res里。由于是unsigned int,所以 2147483648 (10000000000000000000000000000000) 应该返回 1 (00000000000000000000000000000001)。 还有一些神牛的解法在reference里,大都只要几个instruction就可以完成...比较好的有Bit Twiddling Hacks以及Hacker's Delight,要好好学习。
Time Complexity - O(1), Space Complexity - O(1)。
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 >> i) & 1) == 1) { res += (1 << (31 - i)); } } return res; } }
二刷:
还是naive方法...每个比特位先shift然后再&1, 假如结果等于1,那么我们把1左移相同的位数,加到res里。
Java:
Time Complexity - O(1), Space Complexity - O(1)。
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 >> i) & 1) == 1) { res += (1 << 31 - i); } } return res; } }
三刷:
Bit Manipulation,以后一定要Dive Deep
Java:
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int res = 0; for (int i = 31; i >= 0; i--) { if (((n >> i) & 1) == 1) { res += (1 << (31 - i)); } } return res; } }
Reference:
https://graphics.stanford.edu/~seander/bithacks.html
https://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious
http://www.hackersdelight.org/
http://www.hackersdelight.org/hdcodetxt/reverse.c.txt
https://leetcode.com/discuss/27405/o-1-bit-operation-c-solution-8ms