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 */
Code language: Java (java)

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)); } }
Code language: Java (java)

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)); } }
Code language: Java (java)

Alternative 1:

public class BinaryConvert { public static int toBinary(int n) { return Integer.valueOf(Integer.toBinaryString(n)); } }
Code language: Java (java)

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; } }
Code language: Java (java)

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; } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments