十进制数M转N进制

给定一个十进制数M,以及需要转换的进制数N。将十进制数M转化为N进制数 

输入描述:

输入为一行,M(32位整数)、N(2 ≤ N ≤ 16),以空格隔开。

输出描述:

为每个测试实例输出转换后的数,每个输出占一行。如果N大于9,则对应的数字规则参考16进制(比如,10用A表示,等等)

示例1

输入

7 2

输出

111

#include<iostream>
#include<string>
using namespace std;
 
string MtoN(int m, int n)
{
    char table[16];       //依次表示01234...9ABCDEF(表示0~15)
    if(m<0)               //负数转换为正数
       m=m*(-1);
    for(int i=0;i<16;i++) 
        {
            if(i<10)
                table[i]=i+'0';       //转换为字符是是(加)+'0',不能为(减)-'0'.
            else
                table[i]=i-10+'A'; 
        }
    string res;
    while (m)
    {
        int temp = m%n;
        char t = table[temp];
        res =t+res;
        m = m / n;
    }  
    return res;
}
 
int main()
{
    int m,n;
    while(cin >> m >> n)
    {
      string res = MtoN(m, n);
      if(m<0)        //当m为负数时,输出需要加上负号"-"
         cout<<"-";
      cout << res << endl;
    }
}
    原文作者:进制转换
    原文地址: https://blog.csdn.net/sinat_33718563/article/details/77683689
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞