用栈将十进制转化为十六进制

在这里插入图片描述

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 100
using namespace std;
typedef int ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
int InitStack(SqStack &S) 
{
S.base=new ElemType[MAXSIZE];
if(!S.base) return false;
S.top=S.base;
S.stacksize=MAXSIZE;
return true;                                      
}
int Spush(SqStack &S,ElemType e)
{
if(S.top-S.base==S.stacksize) return false;
*S.top++=e;
return true; 
}
int GetTop(SqStack &S)
{
return *(S.top-1);
}
void pop(SqStack &S)
{
S.top--;
}
int transform(int n)
{
SqStack S;
int a,b,i=0;
char str[MAXSIZE];
InitStack(S);
while(n>0)
{
a=n%16;
Spush(S,a);
n=n/16;
}
while((S.top-S.base)!=0)
{

a=GetTop(S);
if(a<10)
{
str[i]=a+'0';
}
else 
{
str[i]=a+'A'-10;
}
pop(S); 
i++;
}
str[i]='\0';
for(i=0;str[i]!='\0';i++)
{
cout<<str[i];
}
}
int main()
{
int e;
cin>>e;
transform(e);
}

```c++
#include<cstdio>
#include<iostream>
#include<cstdlib>
using namespace std;
typedef int datatype;
typedef struct linkstack
{
	datatype data;
	struct linkstack *next;
}linkstack;
void initstack(linkstack *top)
{//初始化 
	top->next=NULL; 
}
void push(linkstack *top,datatype x)
{
	linkstack *p;
	p=(linkstack *)malloc(sizeof(linkstack));
	p->next=top->next;
	top->next=p;
	p->data=x;
}
int pop(linkstack *top)
{
	linkstack *p;
	int x;
	p=top->next;
	top->next=p->next;
	x=p->data;free(p);
	return x;
}
int main()
{
	int num;
	linkstack *top;
	printf("请输入你要转换的数字:");
	scanf("%d",&num);
	top=(linkstack *)malloc(sizeof(linkstack));
	initstack(top);
	while(num!=0)
	{
		push(top,num%16);
		num/=16;
	 } 
	 printf("转换后的数字为:");
	 while(top->next!=NULL)
	 {
	 	num=pop(top);
	 	if(num<10)
	 	printf("%d",num);
		 else
		 {
		 	num-=10;
		 	printf("%c",'A'+num);
		  } 
	  } 
	  printf("\n");
	  return 0;
}
  • 9
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值