文章

49

粉丝

49

获赞

8

访问

11.6k

头像
80%的没用long。m转10,10转n。
P1422 清华大学/厦门大学机试题
发布于2024年3月15日 09:28
阅读数 268

#include <cmath>
#include <iostream>
#include <vector>
using namespace std;

/*m进制转十进制*/
long m_to_ten(int m, string s)
{
    long r = 0;
	int i = 0;
	int n = s.size();
	vector<int> a(n);
	for (int j = 0; j < n; j++)
	{
		if (s[j] >= 'A' && s[j] <= 'Z')
		{
			a[j] = s[j] - 'A' + 10;
		}
		else
		{
			a[j] = s[j] - '0';
		}
	}
	while (i < n)
	{
		r += a[i] * pow(m, n - i - 1);
		i++;
	}
	return r;
}

/*十进制转n进制*/
void ten_to_n(long x, int n)
{
	vector<char> r(0);
	while (x)
	{
		if (x % n > 9)
		{
			r.push_back(x % n + 'a' - 10);
		}
		else
		{
			r.push_back(x % n + '0');
		}
		x /= n;
	}
	for (auto i = r.rbegin(); i != r.rend(); i++)
	{
		cout << *i;
	}
	cout << endl;
}

int main()
{
	string s;
	int m, n;
	while (cin >> m >> n >> s)
	{
		long x = m_to_ten(m, s);
		ten_to_n(x, n);
	}
	return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发