技术笔试面试

数值转换-栈的应用

数值转换是计算机实现计算的基本问题,其解决方法有很多,其中一个简单算法是这样的:
N=(N div d)*d + N mod d (其中:div为整除运算,mod为求余运算)
如:(1348)10=(2504)8,其运算过程如下:

N   N div 8  N mod 8

1348    168      4

168     21       0

21      2        5

2       0        2

最后结果就是2504.

数值转换的源代码实现(略去了头文件):

#define STACK_INIT_SIZE 8
#define STACK_INCREMENT 8

typedef struct
{
int *base;
int *top;
int stacksize;
}mystack;

void init_stack(mystack *S)
{
S->base=(int *)malloc(STACK_INIT_SIZE*sizeof(int));
if(S->base==NULL)exit(1);
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
}

void push_stack(mystack *S,int e)
{
        if(S->top-S->base>=S->stacksize){
                S->base=(int *)realloc(S->base,(S->stacksize+STACK_INCREMENT)*sizeof(int));
                if(S->base==NULL)exit(1);
                S->top=S->base+S->stacksize;
                S->stacksize+=STACK_INCREMENT;
        }
        *(S->top++)=e;
}

int pop_stack(mystack *S,int *e)
{
        if(S->top==S->base) return 3;
        *e=*(--(S->top));
}

int main()
{
        mystack S;
        init_stack(&S);
        int d=8;
        int num=1348;
        printf("Value transfer:\n");
        printf("Decimal:%d\n",num);
        int popnum;
        while(num!=0){
                push_stack(&S,num%d);
                num=num/d;
        }
        printf("%d-based code:");
        while(pop_stack(&S,&popnum)!=3){
                printf("%d",popnum);
        }
        printf("\n");
        return 0;
}

over~

3条评论

  1. 也来写写:
    unsigned int translate(/*unsigned int num, unsigned int bit*/)
    {
    list vec_num;
    unsigned int d=8;
    unsigned int num=1348;
    printf(“Value transfer:\n”);
    printf(“Decimal:%d\n”,num);
    unsigned int popnum;
    unsigned int return_value = 0;
    while(num!=0)
    {
    vec_num.push_front(num%d);
    num=num/d;
    }
    list::iterator it_num = vec_num.begin();
    for( ; it_num != vec_end(); it_num++)
    {
    return_value = return_value*10 + (*it_num);
    }
    return return_value;
    }

发表您的评论

请您放心,您的信息会被严格保密。必填项已标识 *