[英]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.