Reverse Bits | LeetCode
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
here are several methods of reversing the bits of an unsigned integer. Here, we devise an algorithm using the XOR swap trick, and then optimize it using a divide and conquer methodology.
https://zyfu0408.gitbooks.io/interview-preparation/content/bit-manipulation/bit.html
这题的input需要当成unsigned value来做,所以我们在看当前位是不是1的时候,要用>>>,而不是>>。
public int reverseBits(int n) {
int result = 0;
for(int i=0; i<32; i++) {
result += ((n>>i)&1) << (31-i);
}
return result;
}
public int reverseBits(int n) {
int result = 0;
for(int i=0; i<32; i++) {
int bit = (n>>i)&1;
result |= bit<<(31-i); // 注意这边是用 |= 而不是+=
}
return result;
}
X. http://www.cnblogs.com/grandyang/p/4321355.html
https://leetcode.com/discuss/28657/concise-java-solution-300ms
public long reverseBits(int n) { long result = 0; for (int i = 0; i < 31; i++) { result = result + (n & 1); n >>>= 1; result <<= 1; } return result; }
https://leetcode.com/discuss/32301/concise-java-solution
public int reverseBits(int n) { int result = 0; for (int i = 0; i < 32; ++i) { result = result<<1 | (n & 1); n >>>= 1; } return result;
}
We only need to perform the swap when the ith bit and the jth bit are different. To test if two bits are different, we could use the XOR operation. Then, we need to toggle both ith and jth bits. We could apply the XOR operation again. By XOR-ing the ith and jth bit with 1, both bits are toggled.The XOR swap trick O(n)
The divide and conquer approach: log(n)
https://discuss.leetcode.com/topic/36026/what-s-with-the-follow-up
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?
http://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/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).
here are several methods of reversing the bits of an unsigned integer. Here, we devise an algorithm using the XOR swap trick, and then optimize it using a divide and conquer methodology.
https://zyfu0408.gitbooks.io/interview-preparation/content/bit-manipulation/bit.html
这题的input需要当成unsigned value来做,所以我们在看当前位是不是1的时候,要用>>>,而不是>>。
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
if ((n >>> i & 1) == 1) {
result |= 1 << (31 - i);
}
}
return result;
}
https://gist.github.com/gcrfelix/1ae01e0e5d48332a06fapublic int reverseBits(int n) {
int result = 0;
for(int i=0; i<32; i++) {
result += ((n>>i)&1) << (31-i);
}
return result;
}
public int reverseBits(int n) {
int result = 0;
for(int i=0; i<32; i++) {
int bit = (n>>i)&1;
result |= bit<<(31-i); // 注意这边是用 |= 而不是+=
}
return result;
}
X. http://www.cnblogs.com/grandyang/p/4321355.html
uint32_t reverseBits(uint32_t n) { uint32_t res = 0; for (int i = 0; i < 32; ++i) { if (n & 1 == 1) { res = (res << 1) + 1; } else { res = res << 1; } n = n >> 1; } return res; }
我们可以简化上面的代码,去掉if...else...结构,可以结果res左移一位,然后再判断n的最低位是否为1,是的话那么结果res加上1,然后将n右移一位即可,代码如下:
uint32_t reverseBits(uint32_t n) { uint32_t res = 0; for (int i = 0; i < 32; ++i) { res <<= 1; if ((n & 1) == 1) ++res; n >>= 1; } return res; }
uint32_t reverseBits(uint32_t n) { uint32_t res = 0; for (int i = 0; i < 32; ++i) { res = (res << 1) | (n & 1); n >>= 1; } return res; }
public long reverseBits(int n) { long result = 0; for (int i = 0; i < 31; i++) { result = result + (n & 1); n >>>= 1; result <<= 1; } return result; }
https://leetcode.com/discuss/32301/concise-java-solution
public int reverseBits(int n) { int result = 0; for (int i = 0; i < 32; ++i) { result = result<<1 | (n & 1); n >>>= 1; } return result;
}
We only need to perform the swap when the ith bit and the jth bit are different. To test if two bits are different, we could use the XOR operation. Then, we need to toggle both ith and jth bits. We could apply the XOR operation again. By XOR-ing the ith and jth bit with 1, both bits are toggled.The XOR swap trick O(n)
typedef unsigned int uint;
uint swapBits(uint x, uint i, uint j) {
uint lo = ((x >> i) & 1);
uint hi = ((x >> j) & 1);
if (lo ^ hi) {
x ^= ((1U << i) | (1U << j));
}
return x;
}
uint reverseXor(uint x) {
uint n = sizeof(x) * 8;
for (uint i = 0; i < n/2; i++) {
x = swapBits(x, i, n-i-1);
}
return x;
}
http://www.programcreek.com/2014/03/leetcode-reverse-bits-java/public int reverseBits(int n) { for (int i = 0; i < 16; i++) { n = swapBits(n, i, 32 - i - 1); } return n; } public int swapBits(int n, int i, int j) { int a = (n >> i) & 1; int b = (n >> j) & 1; if ((a ^ b) != 0) { return n ^= (1 << i) | (1 << j); } return n; } |
The first step is to swap all odd and even bits. After that swap consecutive pairs of bits, and so on…Therefore, only a total of log(n) operations are necessary.
The below code shows a specific case where n == 32, but it could be easily adapted to larger n‘s as well.
Method1 – Simple
Loop through all the bits of an integer. If a bit at ith position is set in the i/p no. then set the bit at (NO_OF_BITS – 1) – i in o/p. Where NO_OF_BITS is number of bits present in the given number.
Loop through all the bits of an integer. If a bit at ith position is set in the i/p no. then set the bit at (NO_OF_BITS – 1) – i in o/p. Where NO_OF_BITS is number of bits present in the given number.
unsigned int reverseBits(unsigned int num) { unsigned int NO_OF_BITS = sizeof (num) * 8; unsigned int reverse_num = 0, i, temp; for (i = 0; i < NO_OF_BITS; i++) { temp = (num & (1 << i)); if (temp) reverse_num |= (1 << ((NO_OF_BITS - 1) - i)); } return reverse_num; } |
Method 2 – Standard
The idea is to keep putting set bits of the num in reverse_num until num becomes zero. After num becomes zero, shift the remaining bits of reverse_num.
The idea is to keep putting set bits of the num in reverse_num until num becomes zero. After num becomes zero, shift the remaining bits of reverse_num.
Let num is stored using 8 bits and num be 00000110. After the loop you will get reverse_num as 00000011. Now you need to left shift reverse_num 5 more times and you get the exact reverse 01100000.
unsigned int reverseBits(unsigned int num) { unsigned int count = sizeof (num) * 8 - 1; unsigned int reverse_num = num; num >>= 1; while (num) { reverse_num <<= 1; reverse_num |= num & 1; num >>= 1; count--; } reverse_num <<= count; return reverse_num; } |
Method 3 – Lookup Table:
We can reverse the bits of a number in O(1) if we know the size of the number. We can implement it using look up table. Go through the below link for details. You will find some more interesting bit related stuff there.
http://blog.csdn.net/ever223/article/details/44537445We can reverse the bits of a number in O(1) if we know the size of the number. We can implement it using look up table. Go through the below link for details. You will find some more interesting bit related stuff there.
https://discuss.leetcode.com/topic/36026/what-s-with-the-follow-up
OK, first off, here is the Hacker's Delight (figure 7-1) classics in Java:
public int reverseBits(int n) {
// note: mutating formal parameter
n = ((n & 0x5555_5555) << 1) | ((n >>> 1) & 0x5555_5555);
n = ((n & 0x3333_3333) << 2) | ((n >>> 2) & 0x3333_3333);
n = ((n & 0x0F0F_0F0F) << 4) | ((n >>> 4) & 0x0F0F_0F0F);
return (n >>> 24) | ((n >>> 8) & 0xFF00) | ((n & 0xFF00) << 8) | (n << 24);
}
It's quite obvious once you figure it out. Just reverse bits in pairs, then reverse pairs in quadruples, then reverse quadruples in “octuples” (well, bytes or octets), then just reverse bytes. It may seem computation-heavy, but considering that bitwise and shift operations are among the fastest and that it will probably all be done in registers (and the code even minimizes the number of constants involved!), it will be very fast. In fact, that's exactly what
Integer.reverse
does.
Now, I see a lot of solutions using a cache. In fact, we can do even better. Suppose our function is called so many times that initialization time doesn't really matter. So it could look like this:
private static final int[] map = new int[65536];
static {
for (int i = 0; i <= 65535; ++i) {
int n = i;
n = ((n & 0x5555) << 1) | ((n >>> 1) & 0x5555);
n = ((n & 0x3333) << 2) | ((n >>> 2) & 0x3333);
n = ((n & 0x0F0F) << 4) | ((n >>> 4) & 0x0F0F);
map[i] = ((n >>> 8) | (n << 8)) & 0xFFFF;
}
}
// you need treat n as an unsigned value
public int reverseBits(int n) {
return (map[n & 0xFFFF] << 16) | map[n >>> 16];
}
Now class loading will be slow, but then the function will be amazingly fast, as there are only two shifts and one bitwise AND involved. Or will it? Now instead of a lot of arithmetics we have two table lookups. Not to mention this could be hard on cache, memory read operations are obviously much slower than in-register bitwise arithmetics. Maybe changing shorts to bytes can be easier on cache, but then combining the whole thing will look very much like the last [HD] line which is about half of the job. Plus four table lookups.
The solution above runs in 55 ms, by the way, while the first one runs in 2. But I don't know whether the OJ loads the class each time for every test case, and there's probably not enough test cases for the “improvement” above to work (assuming it works at all).
So, my question is, isn't the follow-up basically asking to do a premature optimization that not only won't make things any better, but in fact could make it much worse? Or maybe that's exactly the point? Maybe we should answer that using a table is a bad idea and that we should concentrate on optimizing our math instead, referring to [HD] and
Read full article from Reverse Bits | LeetCodeInteger.reverse
?