Search⌘ K
AI Features

Solution Review: Convert Decimal Number to Binary Number

Explore how to implement a recursive method to convert decimal numbers into their binary equivalents. Understand the base and recursive cases, and see how the method reduces the input in each call while building the binary result.

Solution: From Decimal to Binary

Java
class ChallengeClass {
public static int decimalToBinary(int decimalNum) {
if (decimalNum == 0) {
return 0;
}
else {
return (decimalNum%2 + 10*decimalToBinary(decimalNum/2));
}
}
public static void main( String args[] ) {
int input = 27;
int result = decimalToBinary(input);
System.out.println("The binary form of " + input + " is: " + result);
}
}

Understanding the Code

In the code above, the method decimalToBinary is a recursive method, since it ...