154k views
0 votes
Write a function convert (int n, int base) that uses stack to convert a positive integer n to any base between 2 and 9. You may use simple iteration continually divides the decimal number by base and keeps track of the remainder by using a stack. Please use the methods from ADT Stack below. Write a program to test your function.

1 Answer

1 vote

Answer:

import java.util.*;

public class DemoStack {

public static void convert(int n, int base) {

Stack<Integer> st = new Stack<Integer>();

int temp = n ;

while(n !=0) {

st.push(n % base);

n = n / base ;

}

System.out.printf("The number %d in base %d : ", temp, base);

while(!st.isEmpty()) {

System.out.print(st.pop());

}

}

public static void main(String{} args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter number : ");

int n = sc.nextInt();

System.out.print("Enter base : ");

int base = sc.nextInt();

convert(n, base);

}

}

Step-by-step explanation:

Code is written in JAVA.

This code displays:

1) Enter number : 'x'

2) Enter base : 'y'

3) The number 'x' in base 'y' : abcdefg

User Duvid
by
6.0k points