Write a method called toBinary that accepts an integer as a parameter and returns a String containing that integer’s binary representation. For example, the call of printBinary(44) should return "101100".
public class DecimalToBinary {
public static void toBinary(int value) {
// take an array to store the binary value
int[] binaryArray = new int[65];
// j to represent index value
int j = 0;
while (value > 0) {
binaryArray[j++] = value % 2;
value = value / 2;
}
// array was stored in reverse order
// use forloop to print it right order
for (int i = j - 1; i >= 0; i--) {
System.out.print(binaryArray[i]);
}
System.out.println();
}
public static void main(String[] args) {
DecimalToBinary.toBinary(6654654);
DecimalToBinary.toBinary(32);
DecimalToBinary.toBinary(66);
DecimalToBinary.toBinary(2);
}
}
Output:
11001011000101010111110
100000
1000010
10