使用栈的 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP