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
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短