Reverse the Bits in an Integer in Java


The challenge

Write a function that reverses the bits in an integer.

For example, the number 417 is 110100001 in binary. Reversing the binary is 100001011 which is 267.

You can assume that the number is not negative.

The solution in Java code

Option 1:

import static java.lang.Integer.*;

interface BitsOfInteger {
  static int reverse_bits(int n) {
    return parseInt(new StringBuilder(toBinaryString(n)).reverse() + "", 2);
  }
}

Option 2:

public class BitsOfInteger {
  public static int reverse_bits(int n) {
    return Integer.parseInt(new StringBuilder().append(Integer.toBinaryString(n)).reverse().toString(), 2);
  }
}

Option 3:

public class BitsOfInteger {
  public static int reverse_bits(int n) {
    int toReturn = 0;
    while (n>0){
      int mask = n%2;
      toReturn <<=1;
      toReturn |= mask;
      n >>= 1;
    }
    return toReturn;
  }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Test
    public void fixed_tests() {
        assertEquals(BitsOfInteger.reverse_bits(417), 267);
        assertEquals(BitsOfInteger.reverse_bits(267), 417);
        assertEquals(BitsOfInteger.reverse_bits(0), 0);
        assertEquals(BitsOfInteger.reverse_bits(2017), 1087);
        assertEquals(BitsOfInteger.reverse_bits(1023), 1023);
        assertEquals(BitsOfInteger.reverse_bits(1024), 1);
    }
}