十进制转n进制栈和非栈两种实现方式(C语言版)

原创文章,欢迎转载,转载请注明作者和链接。

#include <iostream>
#include <cstring>
#include <malloc.h>
#include <cmath>
#include <algorithm>
using namespace std;

/*
用栈实现
*/
#define STACK_SIZE 100 //栈初始空间大小
#define STACK_INCREMENT 10//增加空间

typedef struct SqStack{
	int *top;
	int *base;
	int stacksize;//栈当前存储空间
}S;
/*初始化空栈*/
void InitStack(S &s)
{
	s.base = (int *)malloc( STACK_SIZE *sizeof(int));
	s.stacksize = STACK_SIZE;
	s.top = s.base;
}
bool IsEmpty(S s)
{
	if(s.base == s.top)
		return true;
	else 
		return false;
}
void GetTop(S s, int &e)
{
	if(s.top != s.base)
		e = *(s.top - 1);
}
void push(S &s,int e)
{
	if(s.top - s.base >= s.stacksize){
		s.base = (int *)realloc( s.base, (s.stacksize + STACK_INCREMENT)*sizeof(int));
		s.top = s.base + s.stacksize;
		s.stacksize += STACK_INCREMENT;
	}
	
	*(s.top) = e;	
	s.top ++; 
}
void pop(S &s, int &e)
{
	if( s.top != s.base){
		s.top --;
		e = *(s.top);
	}
}

string convert(S &s, int num, int n)//十进制数num转换成n进制数
{
	//InitStack(s);
	do{
		push(s, num % n);
		num /= n;
	}while(num != 0);
	
	string new_num = "";
	int e;
	while( !IsEmpty(s)){
		pop(s, e);
		if(e > 9){//十六进制时为字母
			e = e + 55;
			new_num += e + '0';//注意,此处不要忘了加'0',int型转char型,+'0';char型转int型,-'0'
		}
		else//二进制或八进制
			new_num += e + '0';
	}
 
	return new_num;
}

/*非栈实现*/
string convert1(int num, int n )
{
	string new_num = "";//存放转换后的进制数,由于辗转相除先得到的余数是转换后的结果的低位数,所以最后需要逆序
	int c = 0;//余数
	do{
		c = num % n;
		if(c > 9){
			c = c + 55;//如果是十六进制,需要加55,得到对应十六进制数的ascII值,比如若c=10,则应为A,而A的ascII值为65.
		}
		new_num += c + '0';//
		num /= n;
	}while(num != 0);
	
	reverse(new_num.begin(), new_num.end());
	return new_num;
}
int main()
{
	int num, n;//要转换的十进制数和要转换成的进制
	S s;
	InitStack(s); //存放辗转相除的余数
	cout << "输入要转换的十进制数以及要转换成的进制" << endl;
	cin >> num;
	cin >> n;
	//string new_num = convert(s, num, n);
	string new_num = convert1( num, n);
	cout << "十进制数" << num << "转换为"  << n << "进制后为" << new_num << endl; 
	return 0;
}
    原文作者:进制转换
    原文地址: https://blog.csdn.net/Mary19920410/article/details/64441651
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞