...

/

Solution Review: Convert Decimal Number to Binary Number

Solution Review: Convert Decimal Number to Binary Number

This lesson provides a detailed review of the solution to the challenge in the previous lesson.

Solution: From Decimal to Binary

Press + to interact
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 calls itself in the method body. Below is an explanation of the above code:

Driver Method

  • In the main code, we have defined an integer variable, an input that represents the decimal number that is to be converted to its equivalent binary number.

  • The method decimalToBinary is called on line 14 and takes the input variable as its argument.

  • The System.out.println command on line 15 prints the integer value that returned from the decimalToBinary method.

Recursive Method

  • The return type of this method is int because the binary number will always be in an integer form.

  • The decimalToBinary method takes in only one integer, decimalNum, as its input parameter.

  • It consists of a base case and a recursive case both of which are explained in detail below.

Base Case

  • The base case makes sure that if or when the decimalNum equals to 00, the method should return 00 and get terminated.

Recursive Case

  • If the base condition does not compute to be true, the method enters the else block at line 8, where the recursive call is made. Note that in this recursive call, the input parameter is (decimalNum/2), which is multiplied by 1010, and decimalNum%2 is further added to it.

  • With each recursive call, the input parameter decimalNum is reduced by half.

Let us look at the example below to see why this input parameter is passed to the recursive function.

Let the decimal number be 99 ...