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;
}

4 thoughts on “LeetCode – Reverse Bits (Java)”

  1. I think this is more easier to understand.
    Pull from the lower end and push to the reversed string.


    int reverseBits(int num)
    {
    int reverse = 0;

    for (int i = 0 ; i >= 1)
    {
    reverse <<= 1;
    if (num % 2 == 1) reverse += 1;
    }
    }

  2. 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

  3. 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

Leave a Comment