使用堆栈实现十进制转换成二进制

计算十进制转换成二进制的方式非常类似堆栈的后进先出的方式(LIFO),所以可以使用下面的代码实现

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

#define SIZE_INTI_STACK 100 //确定栈的初始长度
#define SIZE_OF_NEW_STACK 10 //确定栈每次延展的长度
#define true 1 //个人习惯定义的类似布尔类型数据
#define false 0

typedef struct binary
{
    int *base;
    int *top;
    int sizeOfStack;
}BINARY;

int initStack(BINARY *tempStack);
int destoryStack(BINARY *tempStack);
int push(BINARY *tempStack, int temp);
int visitStack(BINARY tempStack);

int main()
{
    int number, temp;
    BINARY myBinary;

    while(true)
    {
        initStack(&myBinary);

        printf("please input a number : ");
        scanf("%d", &number);
        while(number != 0)
        {
            //每次除以二,然后压入栈中,之后再按栈的顺序取出数据打印就可以了
            temp = number%2;
            number = number / 2;
            push(&myBinary, temp);
        }
        if(number == 0)
        {
            push(&myBinary, number);
        }
        visitStack(myBinary);

        destoryStack(&myBinary);
    }
    return 0;
}

int initStack(BINARY *tempStack)
{
    tempStack->base = (int *) malloc(SIZE_INTI_STACK * sizeof(int));
    if(tempStack->base == NULL)
    {
        printf("fail to get memory!\n");
        exit(1);
    }
    tempStack->top = tempStack->base;
    tempStack->sizeOfStack = SIZE_INTI_STACK;
    return true;
}

int destoryStack(BINARY *tempStack)
{
    free(tempStack->base);
    tempStack->base = NULL;
    tempStack->top = NULL;
    tempStack->sizeOfStack = 0;
    return true;
}

int push(BINARY *tempStack, int temp)
{
    if(tempStack->top - tempStack->base >= tempStack->sizeOfStack)
    {
        tempStack->base = (int *) realloc(tempStack->base, sizeof(int)*SIZE_OF_NEW_STACK);
        if(tempStack->base == NULL)
        {
            printf("fail to get memory\n");
            exit(1);
        }
        tempStack->top = tempStack->base + SIZE_INTI_STACK;
        tempStack->sizeOfStack += SIZE_OF_NEW_STACK;
    }
    *tempStack->top++ = temp;
    return true;
}

int visitStack(BINARY tempStack)
{
    int i = 0;
    if(tempStack.base == tempStack.top)
    {
        printf("have no information!\n");
        return false;
    }
    while(tempStack.base < tempStack.top)
    {
        printf("%d", *(--tempStack.top));
        i++;
        if(i == 4)
        {
            i = 0;
            printf(" ");
        }
    }
    printf("\n");
    return true;
}

但是在输入数据的时候要小心不要输入的数据超过int的数据大小

点赞