I have a program due for my Data Structures tomorrow and I need to figure out how to make it so it converts a number from binary to decimal with using a stack. I was able to figure it out without using a stack but stacks still really confuse me and part of the requirement is to use one. Any help would be awesome, thanks!
You can compare a stack to a pile of plates. You add a plate on the top(push) and normally you take one from the top(pop). Last in first out.
If you have a stack of chars and put 'a', 'b' and 'c' in it and remove them all you get first 'c', them 'b' and finally 'a' back - means in reversed order.
A little hint for your conversion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int binary_do_decimal(const string& input)
{
int output = 0, index = 0;
stack<char> digits; // #include <stack>
// add all digits to the stack
for (char ch: input)
digits.push(ch);
while (!digits.empty())
{
char ch = digits.top();
digits.pop();
// TODO convert to ch to its numerical value and add to output.
// remember that they are in reversed order so the first char is 2^index
}
return output.
}
Hope this makes sense
binary and hex are one to one. You can do it a nibble at a time if you convert it to hex first. You have to do it a bit at a time (4x more work) if you stick to decimal.
I would shift into N directly. I think its
N <<= (*s-'0'); //right?
after thinking about it, its efficient in reverse (integer to string binary) but not string to int to use the nibbles. The above shift is going to be faster than the string comparisons to do a lookup.
Its probably a 'do it this way' assignment. No one would really use a stack for this.