繁体   English   中英

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

[英]How can I use a stack to convert numbers from base 10 to base 2 in C++?

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

我的老师不是最好的。

#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;
}

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

让我们取第一个数字 18。将其视为一个循环。 您使用模要转换为的基数。 一般可应用于任何基础。 一个非常简单的大纲如下:

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++ 代码。 我相信您能够自己设计和编写代码。 其他人已经提供了代码。

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM