此题主要就是利用栈来存储余数,关键是要处理好十六进制的字母入栈及出栈
#include <iostream>
#include <cmath>
#include <stack>
#include <algorithm>
using namespace std;
int main()
{
stack <int > s;
int n,m,flag;
char alp[6]={'A','B','C','D','E','F'};
while(cin>>m>>n)
{
flag=1;
while (m)
{
if(m<0) {m=-m;flag=0;}
if(m%n >= 10)
s.push(alp[(m%n)-10]); //自动将字符转换成整数入栈
else
s.push(m%n);
m/=n;
}
while (!s.empty())
{
if(!flag) {cout<<"-";flag=1;}
if(s.top()>10)
printf("%c",s.top()); //出栈时再转换成字符
else
cout<<s.top();
s.pop();
}
cout<<endl;
}
return 0;
}