Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Java, Consider the following general algorithm for converting a decimal numbe

ID: 3904876 • Letter: I

Question

In Java, Consider the following general algorithm for converting a decimal number to binary:

   String s is an empty string

         Iteration (while number is greater than zero)

   Determine the integer remainder of number / 2

   Append to s the remainder

         Replace the number with number / 2

   End the iteration

If you try this using 13 as your decimal number you’ll get an answer of 1011 which is not correct.  13 in binary is actually 1101.  Write a proper Java method that uses a stack so that the result is correct.   Assume you have access to either an integer or generic stack as described by the assignments.  Do not simply use the stack superficially, you must integrate it into the algorithm.  State any assumptions you are making.

Explanation / Answer

class Main {

public static String btod(int n)

{

// if number is still there, calling recursively

if(n > 0)

{

// adding to the last makes it reverse

return (btod(n / 2) + "" +(n%2));

}

// finally returning

return "";

}

public static void main(String[] args) {

System.out.println(btod(13));

}

}

// Output: 1101

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote