题目描述
输入
输出
示例输入
7 2 23 12 -4 3
示例输出
111 1B-11
#include <stdio.h> #include <stdlib.h> #include<malloc.h> #define STACK_INIT_SIZE 100//存储空间初始分配量 #define STACKINCREMENT 10 //存储空间分配增量 #define OK 1 #define OVERFLOW -1 #define ERROR -2 typedef char SElemType; typedef struct { SElemType *base;//栈底指针 SElemType *top;//栈顶指针 int stacksize; } SqStack;
void InitStack(SqStack &S)// 构造一个空栈S { S.base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType)); if(!S.base) exit(OVERFLOW);//存储分配失败 S.top=S.base; S.stacksize=STACK_INIT_SIZE; }
void Push(SqStack &S,SElemType e) // 插入元素e为新的栈顶元素 { if(S.top-S.base>=S.stacksize) // 当前存储空间已满,增加分配 { S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType)); if(!S.base) exit(OVERFLOW); // 存储分配失败 S.top=S.base+S.stacksize; S.stacksize+=STACKINCREMENT;//增加存储容量 } *S.top++=e; }
int Pop(SqStack &S,SElemType &e) { if(S.top==S.base) return ERROR; e=*--S.top; return OK; }
void conversion(SqStack &S,int n,int r)//将十进制数n转换为r进制数; { char t; int h,flag=0; if(n==0)//判断n为0时; { printf("0"); } else { while(n) { if(n<0)//当n为负数时; { n=-n; flag=1;//标记是否将-进栈; } h=n%r; if(h<10&&h>=0) t=h+'0';//数字符的转换; else if(h>=10&&h<16) { switch(h-9) { case 1: t='A'; break; case 2: t='B'; break; case 3: t='C'; break; case 4: t='D'; break; case 5: t='E'; break; case 6: t='F'; break; } } n=n/r; Push(S,t);//进栈; } if(flag==1) Push(S,'-'); } }
void PutStack(SqStack &S)//栈内元素的输出; { while(S.top>S.base) { S.top--; printf("%c",*S.top); } printf("\n"); }
int main() { int n;int r; while(~scanf("%d%d",&n,&r)) { SqStack S;//栈的定义; InitStack(S);//栈的初始化; conversion(S,n,r);//十进制n转化为r进制; PutStack(S);//栈元素的输出; } return 0; }