LeetCode – Reverse Bits (Java)

Problem

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?

Related problem: Reverse Integer

Java Solution

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;
}
Category >> Algorithms >> Interview >> Java  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Zhongyuan Zhang

    is this the optimised solution?

    map = {0: 0, 1: 8, 2: 4, 3: 12, 4: 2, 5: 10, 6: 6, 7: 14, 8: 1, 9: 9, 10: 5, 11: 13, 12: 3, 13: 11, 14: 7, 15: 15}
    res = 0
    for i in range(8):
    res <>= 4
    return res

  • Walden

    public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
    int answer = 0;
    for (int i = 0; i < 32; i++) {
    answer <> x) & 1);
    }
    return answer;
    }
    }
    this was a 2ms java solution