2-36进制数的任意转换

#include<iostream>
#include<string>
#include<cmath>
#include<stack>
using namespace std;

stack<char> NumChange(int from, int to, string num)
{
	stack<char> result;
	unsigned long long dec = 0ULL;
	int j = 0;
	bool largeC = false;
	if (to < 2 || to > 36 || from < 2 || from > 36)
		return result;
	if (num[0] == '-')
		j = 1;
	for (int i = j; i < num.length(); ++i)
	{
		if (num[i] >= 'a')
			dec += (10 + num[i] - 'a')*pow(from, num.length() - i - 1);
		else if (num[i] >= 'A')
		{
			dec += (10 + num[i] - 'A')*pow(from, num.length() - i - 1);
			largeC = true;
		}
		else
			dec += (num[i] - '0')*pow(from, num.length() - i - 1);
	}
	if (j)
		dec = ~(dec - 1);
	while (dec)
	{
		int temp = dec%to;
		if (temp >= 10)
		{
			if(largeC)
				result.push(char(temp - 10 + 'A'));
			else
				result.push(char(temp - 10 + 'a'));
		}
		else
			result.push(char(temp + '0'));
		dec /= to;
	}
	return result;
}

int main(void)
{
	stack<char>result;
	int from, to;
	string num;
	while (true)
	{
		cin >> from >> to >> num;
		result = NumChange(from, to, num);
		while (!result.empty())
		{
			cout << result.top();
			result.pop();
		}
		cout << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值