...
/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.
We'll cover the following...
Solution: From Decimal to Binary
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
maincode, we have defined an integer variable, aninputthat represents the decimal number that is to be converted to its equivalent binary number. -
The method
decimalToBinaryis called on line 14 and takes theinputvariable as its argument. -
The
System.out.printlncommand on line 15 prints the integer value that returned from thedecimalToBinarymethod.
Recursive Method
-
The return type of this method is
intbecause the binary number will always be in an integer form. -
The
decimalToBinarymethod 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
decimalNumequals to , the method should return and get terminated.
Recursive Case
-
If the base condition does not compute to be true, the method enters the
elseblock 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 , anddecimalNum%2is further added to it. -
With each recursive call, the input parameter
decimalNumis 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 ...