利用栈实现十进制转换为二进制的代码
时间: 2024-05-11 11:19:25 浏览: 10
以下是利用栈实现十进制转换为二进制的代码(使用C++实现):
```c++
#include <iostream>
#include <stack>
using namespace std;
void decimalToBinary(int decimal) {
stack<int> binaryStack; // 创建一个用于存放二进制数的栈
// 将十进制数转换为二进制数
while (decimal > 0) {
binaryStack.push(decimal % 2); // 将二进制数的每一位压入栈中
decimal /= 2; // 更新十进制数
}
// 输出转换后的二进制数
cout << "Binary: ";
while (!binaryStack.empty()) {
cout << binaryStack.top(); // 输出栈顶元素
binaryStack.pop(); // 弹出栈顶元素
}
cout << endl;
}
int main() {
int decimal;
cout << "Enter a decimal number: ";
cin >> decimal;
decimalToBinary(decimal);
return 0;
}
```
运行程序后,输入一个十进制数,程序将输出其对应的二进制数。
相关问题
利用栈实现十进制转换为二进制
可以按照以下步骤利用栈实现十进制转换为二进制:
1. 将十进制数不断除以2,将余数入栈,直到商为0停止;
2. 依次从栈中取出余数,组成二进制数。
以下是实现的示例代码(假设使用链式栈):
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, data):
node = Node(data)
node.next = self.top
self.top = node
def pop(self):
if self.top is None:
return None
data = self.top.data
self.top = self.top.next
return data
def is_empty(self):
return self.top is None
def decimal_to_binary(decimal):
stack = Stack()
while decimal > 0:
remainder = decimal % 2
stack.push(remainder)
decimal //= 2
binary = ''
while not stack.is_empty():
binary += str(stack.pop())
return binary
```
我们可以调用 `decimal_to_binary` 函数来进行测试:
```python
print(decimal_to_binary(10)) # 输出 1010
print(decimal_to_binary(27)) # 输出 11011
```
C语言利用栈实现十进制转换成其他进制的代码
以下是C语言利用栈实现十进制转换成其他进制的代码,以转换成二进制为例:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 100
typedef struct {
int top;
int data[MAX_STACK_SIZE];
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
void push(Stack *s, int value) {
if (s->top < MAX_STACK_SIZE - 1) {
s->data[++s->top] = value;
} else {
printf("Stack is full.\n");
}
}
int pop(Stack *s) {
if (s->top >= 0) {
return s->data[s->top--];
} else {
printf("Stack is empty.\n");
return -1;
}
}
int isEmpty(Stack *s) {
return s->top == -1;
}
void convertDecimalToBinary(int decimal) {
Stack s;
initStack(&s);
while (decimal > 0) {
push(&s, decimal % 2);
decimal /= 2;
}
printf("Binary: ");
while (!isEmpty(&s)) {
printf("%d", pop(&s));
}
printf("\n");
}
int main() {
int decimal;
printf("Enter a decimal number: ");
scanf("%d", &decimal);
convertDecimalToBinary(decimal);
return 0;
}
```
解释:
首先定义了一个栈的结构体,包含栈顶指针和数据数组。然后定义了栈的初始化、入栈、出栈、判空等基本操作。
接下来定义了一个函数`convertDecimalToBinary`,用于将十进制数转换成二进制数。该函数创建了一个栈`s`,然后使用循环将十进制数的每一位转换成二进制数并入栈。最后,从栈顶开始依次出栈并打印到控制台。
在`main`函数中,首先读入用户输入的十进制数,然后调用`convertDecimalToBinary`函数将其转换成二进制数并打印到控制台。
你可以根据需要修改代码来实现将十进制数转换成其他进制数。