0

I am having a hard time figuring out the answer to a homework assignment for Programming 1 class. The assignment is prompt a user for input (up to 4 bits) in binary, and convert it to the decimal equivalent. Using loops, conditional statements, ParseInt, and anything other than the modulus operator and other math operators are not allowed.

I am having trouble with the mathematical aspect, I think once I understand how to use the modulus operator to answer the question I would be able to write the code for it.

I have searched and have not been able to find anything that was able to help.

Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80

1 Answers1

0

You should be getting the number values of each position and add them using the power of 2 to get back the original number.

    double num = 1110;
    double ones = Math.floor(num % 10);
    double tens = Math.floor(num/10 % 10);
    double hundreds = Math.floor(num/100 % 10);
    double thousands = Math.floor(num %10000 /1000);
    double tenThousands = Math.floor(num / 10000 % 10);

    double original = (ones * 1) +
                      (tens * 2) + 
                      (hundreds * 4) +
                      (thousands * 8);


    System.out.println(num);
    System.out.println("ones: " +ones);
    System.out.println("tens: " +tens);
    System.out.println("hundreds: " +hundreds);
    System.out.println("thousands: " + thousands);
    System.out.println("original number : " + original);
Chit Khine
  • 830
  • 1
  • 13
  • 34
  • Thanks Chit, that works and I understand why its working and the math involved. Thank you again that was a big help as I was stuck on this question. – Mr Bigglesworth Aug 26 '16 at 14:31