Reverse the bits in an integer in Java

0 min read 153 words

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);
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts