How to Convert an Integer to Binary using Java

The challenge

Given a non-negative integer n, write a function toBinary/ToBinary which returns that number in a binary format.

to_binary(1)  /* should return 1 */
to_binary(5)  /* should return 101 */
to_binary(11) /* should return 1011 */

Test cases

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


public class ConvertTest {
    @Test
    public void testToBinary() {
  		assertEquals(1, BinaryConvert.toBinary(1));
  		assertEquals(10, BinaryConvert.toBinary(2));
  		assertEquals(11, BinaryConvert.toBinary(3));
  		assertEquals(101, BinaryConvert.toBinary(5));
    }
}

The solution in Java

public class BinaryConvert {

  public static int toBinary(int n) {
    // Use the `toBinaryString` method of the Integer class
    // convert it back to an `int` using the `parseInt` method of the Integer class
    // return the result
    return Integer.parseInt(Integer.toBinaryString(n));
  }

}

Alternative 1:

public class BinaryConvert {

  public static int toBinary(int n) {
    return Integer.valueOf(Integer.toBinaryString(n));
  }
}

Alternative 2 (doing it all manually):

public class BinaryConvert {

  public static int toBinary(int n) {
        int multiplier = 1;
        int value = 0;
        
        do {
            value += (n % 2) * multiplier;
            n /= 2;
            multiplier *= 10;
        } while (n > 0);
        
        return value;
    }

}

Alternative 3 (doing it in a ternary):

public class BinaryConvert {

  public static int toBinary(int n) {
    return n>1 ? toBinary(n/2) * 10 + n%2 : n;
  }
}
Tags:
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments