I need Help with Base Conversion Write a program that uses recursion to convert
ID: 3840692 • Letter: I
Question
I need Help with Base Conversion
Write a program that uses recursion to convert a base 10 number into a base b number, where b < 10. If the number to be converted is n, then the algorithm to convert n to base b is:
1) Divide n by b. Store the quotient and the remainder.
2) The remainder is the rightmost digit of the final answer.
3) The quotient is now the new number n that you will recursively convert to base b.
4) Repeat step a by calling your recursive method with the quotient and the original base b.
5) Stop when n / b = 0. The remainder at this point will be the first digit of the final answer.
For example, to convert 30 into a base 4 number:
Quotient Remainder
30/4 7 2
7/4 1 3
1/4 0 1
The answer is the remainder column read bottom to top, so 30 (base 10) = 132 (base 4).
A skeleton of the recursive method is given below.
public static String convert(int number, int base)
{
int quotient =
int remainder =
if( )
return( + );
else
return( ) + );
}
Sample Output:
Enter a number to convert: 48
Enter a base to convert to: 8
48 converted into base 8 is 60.
Enter a number to convert: 157
Enter a base to convert to: 2
157 converted into base 2 is 10011101.
Enter a number to convert: 48
Enter a base to convert to: 8
48 converted into base 8 is 60.
Enter a number to convert: 157
Enter a base to convert to: 2
157 converted into base 2 is 10011101.
Explanation / Answer
// BaseConvert.java
import java.util.*;
import java.util.Scanner;
public class BaseConvert
{
public static String convert(int number, int base)
{
int quotient = number / base;
int remainder = number % base;
if (quotient == 0)
{
return Integer.toString(remainder);
}
else
{
return convert(quotient, base) + Integer.toString(remainder);
}
}
public static void main(String[] args)
{
Scanner scanner = null;
int base;
int number;
scanner = new Scanner(System.in);
System.out.print("Enter a number to convert: ");
number = scanner.nextInt();
System.out.print("Enter a base to convert to: ");
base = scanner.nextInt();
if (base < 10)
{
System.out.println(number + " converted into base " +base + " is " + convert(number, base));
}
else
{
System.out.println("base should less than 10");
}
}
}
/*
output:
Enter a number to convert: 48
Enter a base to convert to: 8
48 converted into base 8 is 60
Enter a number to convert: 157
Enter a base to convert to: 2
157 converted into base 2 is 10011101
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.