使用棧的 C++ 程式將十進位制數轉換為二進位制數


在這個問題中,我們將瞭解如何使用棧將十進位制數轉換為二進位制數。眾所周知,十進位制數可以透過將其除以 2 並取餘數來轉換為二進位制數。我們從最後開始取餘數,所以我們可以輕鬆使用棧資料結構來做到這一點。

Input: Decimal number 13
Output: Binary number 1101

演算法

Step 1: Take a number in decimal
Step 2: while the number is greater than 0:
Step 2.1: Push the remainder after dividing the number by 2 into stack.
Step 2.2: set the number as number / 2.
Step 3: Pop elements from stack and print the binary number

示例程式碼

 即時演示

#include<iostream>
#include<stack>
using namespace std;
void dec_to_bin(int number) {
   stack<int> stk;
   while(number > 0) {
      int rem = number % 2; //take remainder
      number = number / 2;
      stk.push(rem);
   }
   while(!stk.empty()) {
      int item;
      item = stk.top();
      stk.pop();
      cout << item;
   }
}
main() {
   int num;
   cout << "Enter a number: ";
   cin >> num;
   dec_to_bin(num);
}

輸出

Enter a number: 18
10010

更新日期:2019 年 7 月 30 日

3 千次以上瀏覽

開啟你的 職業

透過完成該課程來獲得認證

開始學習
廣告