B3619 题解

题目传送门

\(\color{red}{see}\space \color{green}{in}\space \color{blue}{my}\space \color{purple}{blog}\)

小学生又双叒叕来写题解啦!

这题就是 \(10\) 进制转 \(x\) 进制的模板题。

我们可以使用短除法倒取余数实现。

具体如下,这里借用了百度搜索的图片。

那么如何在程序中实现呢?

我们可以使用 while() 语句。

具体如下:

string ans = "";  //存储答案。
while (n != 0)    //模拟短除法。 
{
	ans += dict[n % x];
	n /= x;
}

观察这段代码,大家都会有疑问:dict[n % x] 是神马东西?

dict 数组是数组字典,如下。

string dict = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

到这里,题目就快做完了,但别忘了,还得倒取余数

string t = "";  //倒取余数。
for (int i = ans.length()-1; i >= 0; i--) t += ans[i];

最后,把这些代码拼起来就完事了。

完整代码:

#include <iostream>
#include <cstdio>
using namespace std;
string dict = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string ten_to_x(int n, int x)  //十进制转 x 进制函数。 
{
	string ans = "";
	while (n != 0) //模拟短除法。 
	{
		ans += dict[n % x];
		n /= x;
	}
	string t = "";  //倒取余数。
	for (int i = ans.length()-1; i >= 0; i--) t += ans[i];
	return t; 
}
int main()
{
	int n, x;
	cin >> n >> x;
	cout << ten_to_x(n, x);
	return 0;
}

首发:2022-03-27 10:10:53

posted @ 2022-08-25 00:29  liangbowen  阅读(65)  评论(0编辑  收藏  举报