...

/

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 ...

Access this course and 1400+ top-rated courses and projects.