In: Computer Science
Today, Raphael was asked by his coworker (a math teacher) to help him write a C++ program that converts an integer from decimal to binary. This (kinda annoying) guy recently learned about the usefulness of stacks, and wants Raphael to write a program that does this using stacks. He will not accept any algorithm that doesn't use stacks.
As an illustrative example of the algorithm that Raphael was
asked to implement, say you want to convert 14 into binary. Then
you do the following:
1. 14/2 = 7, remainder is 0.
2. 7/2 = 3, remainder is 1.
3. 3/2 = 1, remainder is 1.
4. 1/2 = 0, remainder is 1.
Then the binary value of 14 is 1110.
Using stacks, write a program for Raphael that takes as input a positive integer n (in decimal), and outputs a string of 0's and 1's which represents n in binary.
#include#include using namespace std; int main() { stack bits; int num; cout << "Enter number: "; cin >> num; while(num != 0) { bits.push(num % 2); num = num / 2; } cout << "binary number: "; while(!bits.empty()) { cout << bits.top(); bits.pop(); } cout << endl; }