如何在C ++中使用堆栈将数字从基数10转换为基数2?

问题描述 投票:-1回答:3

我被赋予了使用堆栈来使用C ++将数字从基数10转换为基数2的任务。我得到了数字18,27,71,107和178.我不知道从哪里开始,我只是想知道是否有人愿意通过编写示例代码并向我解释来帮助我。我的老师不是最好的。

c++ stack
3个回答
1
投票
#include <cstdio>
#include <stack>

int main(void) {
    unsigned int n;
    while(scanf("%u", &n) == 1) { // read a number to convert
        std::stack<int> s; // create stack. it is initialized.
        do {
            s.push(n & 1); // push the "lowest" digit to the stack
        } while ((n >>= 1) > 0); // proceed to next digit until the number becomes 0
        // s.top() is the highest digit here
        while (!s.empty()) { // print the number
            printf("%d", s.top()); // print the "highest" number here
            s.pop(); // proceed to next digit
        }
        putchar('\n');
    }
    return 0;
}

1
投票

具有基数的数字可以相对容易地转换为具有另一个基数的数字。在你的情况下,只有正数。所以我暂时坚持这一点。

让我们取第一个数字18.考虑一个循环。您使用modulo转换为您想要的基数。一般可以应用于任何基地。一个非常简单的大纲如下:

do {
  int x = abs( n % b );
  push x on stack;
} while ( n /= b );

例:

For n=18 it be as follows:
Stack [0]        , n = 18
Stack [0,1]      , n = 9
Stack [0,1,0]    , n = 4
Stack [0,1,0,0]  , n = 2
Stack [0,1,0,0,1], n = 1
Stack [0,1,0,0,1], n = 0 <- terminates here

你从堆栈中读取,像在舞池上一样弹出:

while (stack not empty) {
cout << stack.pop();
}

会给:

10010

这是二进制数18,即基数为2。

我没有编写C ++代码。我相信你能够自己设计和编写代码。其他人已经提供了代码


0
投票
#include <iostream>
#include <stack>
using namespace std;
int main()
{
    int n;
    stack<int> Stack;
    int tmp;
    cout << "Put n:";
    cin>> n;
    cout << endl;
    // Push to stack
    while(n!=0)
    {
        Stack.push(n%2);
        n = n/2;
    }
    // Get back and print out
    while(Stack.size()!=0)
    {
        // get top element in the stack
        tmp = Stack.top();
        // pop it out from stack
        Stack.pop();
        cout << tmp ;
    }
    cout << endl;

    system("pause");
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.