...

/

Solution Review: Decimal to Binary Conversion

Solution Review: Decimal to Binary Conversion

Understand the solution of the Decimal to Binary Conversion exercise in this lesson.

We'll cover the following...

Coding solution

Let’s take a look at the solution first.

Press + to interact
class DecimalToBinary{
public Integer Decimal2Binary(Integer myDecimalNumber) {
if (myDecimalNumber == 0) {
return myDecimalNumber;
}
StringBuilder myBinaryNumber = new StringBuilder();
Integer quotient = myDecimalNumber;
//we keep dividing the quotient until the quotient becomes 0
while (quotient > 0) {
int remainder = quotient % 2;
myBinaryNumber.append(remainder);
quotient /= 2;
}
myBinaryNumber = myBinaryNumber.reverse();
return Integer.valueOf(myBinaryNumber.toString());
}
}
public class DtoB {
public static void main(String []args) {
Integer number = 10;
DecimalToBinary myNumber = new DecimalToBinary();
System.out.print("The binary of " + number + " is " +
myNumber.Decimal2Binary(number));
}
}

Explanation

  • The lines (6 ...