【笔试题】N进制数向M进制数转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LLZK_/article/details/65450317


考虑的就是大于10的数都用字母表示,0~9有10个数字,再加上A~Z有26个字母刚好可以表示36进制数。再考虑就是大数问题,int表示不了怎么办,考虑用字符串。

1、采取模N除N的方式,将原数字转换为10进制数。

2、采用除留余数法,将数字转化为M进制数。

3、逆置字符串。


#include<iostream>
#include<string>
using namespace std;

string* fun(const string number, int n, int m)
{
          string s("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
          unsigned int i = 0;
          int num = 0;
          while (i < number.size())
          {
                   num = num * n + number[i] - '0';
                   i++;
          }

          i = 0;
          string* ret = new string;
          while (num > 0)
          {
                   ret->push_back(s[num%m]);
                   num /= m;
          }

          int begin = 0;
          int end = ret->size() -1;
          while (begin < end)
          {
                   char tmp = (*ret)[begin];
                   (*ret)[begin] = (*ret)[end];
                   (*ret)[end] = tmp;
                   begin++;
                   end--;
          }

          return ret;
}

int main()
{
          string s("162342");
          string *ret = fun(s, 10, 36);
          cout << *ret << endl;
          delete ret;
          ret = NULL;
          system("pause");
          return 0;
}



猜你喜欢

转载自blog.csdn.net/LLZK_/article/details/65450317
今日推荐