解题思路
做了上一题的转十六进制后,这个题的难点升级为了2到16以内的任意进制数字,我们可以用一个char类型的数组或者string字符串来表示一个对应进制所对应的表示,从十一进制开始就出现了字母,因此后面的用字母表示。因此这里也放两种解题代码
ac代码1
#include <iostream>
#include <stack>
using namespace std;
char a[20] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
'D', 'E', 'F' };
int main() {
stack<char> stk;
int n, x;
cin >> n >> x;
while (n != 0) {
stk.push(a[n % x]);
n = n / x;
}
while (!stk.empty()) {
cout << stk.top();
stk.pop();
}
return 0;
}
ac代码2
#include <iostream>
#include <algorithm>
#include<string>
using namespace std;
string s = "0123456789ABCDEF";
int main() {
string ans ="";
int n, x;
cin >> n >> x;
while (n != 0) {
ans += s[n % x];
n = n / x;
}
reverse(ans.begin(),ans.end());
//字符串翻转函数,类似于前一个题解的for循环倒序遍历输出
cout << ans;
return 0;
}