数据结构实验之栈一:进制转换
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
输入一个十进制非负整数,将其转换成对应的 R (2 <= R <= 9) 进制数,并输出。
Input
第一行输入需要转换的十进制非负整数;
第二行输入 R。
Output
输出转换所得的 R 进制数。
Example Input
1279
8
Example Output
2377
代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}ST;
int main()
{
ST *head, *p, *tail;
int n, r;
while(~scanf("%d %d", &n, &r))
{
head = (ST *)malloc(sizeof(ST));//头结点
head->next = NULL;
tail = head;
if(n == 0) {printf("0\n"); continue;}//如果n等于0,无论r等于多少,进制转换,的结果都是0
else
{
while(n > 0)
{
p = (ST *)malloc(sizeof(ST));
p->data = n % r;//对r取余压入栈,
p->next = tail->next;//逆序,插入到头
tail->next = p;
n = n / r;
}
}
for(tail = head->next; tail != NULL; tail = tail->next)
{
printf("%d",tail->data);
}
printf("\n");
}
return 0;
}