In: Computer Science
In C++, type a function function(int n, int base) that converts a positive integer x to any base between 2 and 9. The function HAS to do this using a stack, and using methods from below:
+isEmpty(): boolean
+push(newEntry: ItemType): boolean
+pop(): boolean
+peek(): ItemType
(Also, type a program to test the function).
Hint: could use simple iteration continually divides the decimal number by base and keeps track of the remainder by using a stack.
Program Code Snapshot
Program Sample Input/Output Screenshot
Program Code to copy
#include <bits/stdc++.h>
using namespace std;
// declare Stack class with given methods
class Stack
{
public:
vector<int> data;
void push(int val)
{
data.push_back(val);
}
int pop()
{
int val = data.back();
data.pop_back();
return val;
}
int peek()
{
return data.back();
}
bool isEmpty()
{
return data.size() == 0;
}
};
// converts a positive integer x to any base between 2 and 9
int func(int n, int base)
{
// could use simple iteration continually divides the decimal
// number by base and keeps track of the remainder by using a stack.
Stack stack;
while (n)
{
int remainder = n % base;
stack.push(remainder);
n /= base;
}
int result = 0;
//pop stack and fill result
while (!stack.isEmpty())
{
result = result * 10 + stack.pop();
}
return result;
}
int main()
{
//program to test our function
int n, base;
cout << "Enter number to convert: ";
cin >> n;
cout << "Enter base to covert in: ";
cin >> base;
cout << n << " is base " << base << " = " << func(n, base);
}