根据进制转换的规律本质一直取余即可。
要注意当输入是-2的32次方时,这时候置反会造成上溢出,但是题目的数据没有这么强, 那就算了。如果比较强,还是用long long int 比较好
另外用到了STL里的stack,比用数组存起来然后从末位开始输出的方式比起来逻辑上要简单一点。
#include<cstdio>
#include<stack>
using namespace std;
int main()
{
int N, R;
bool isPos;
//char ch[]={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char ch[]="0123456789ABCDEF";
stack<char> st;
while(scanf("%d %d", &N, &R)==2)
{
isPos = true;
if(N<0)
{
isPos = false;
N = -N;
printf("-");
}
while(N>0)
{
st.push(ch[N%R]);
N /= R;
}
while(!st.empty())
{
printf("%c", st.top());
st.pop();
}
printf("\n");
}
return 0;
}