华为笔试——C++进制转换

题目:2-62进制转换

题目介绍:输入一个n1 进制的整数(包括负数),将其转换成n2 进制,其中n1 、n2 的范围是 [ 2,62 ] 。每个数字的范围是0-9、a-z、A-Z。不用考虑非法输入。

输入:

n1 n2

n1 进制整数

输出:

n2 进制整数

例:

输入:

8 16

-1352460

输出:

-5d530

分析:

这道题目需要考虑几点:负整数的输入;将输入的n1 进制的数转换成10 进制的数,再用长除法将这个10 进制的数转换成 n2 进制的数;a-z和A-Z与其代表的整数的相互转换(char 类型的ASC||码与整数的变换)。

代码如下:

 1 #include <iostream>
 2 #include <string>
 3 #include <math.h>
 4 #include <conio.h>
 5 using namespace std;
 6 int main()
 7 {
 8     string str;
 9     int size;
10     int i = 0;
11     int result = 0;
12     int n = 0;
13     int r[10];//长除法
14     char q[10];
15     int n1, n2;
16     cout << "n1.n2" << endl;
17     cin >> n1 >> n2;
18     cout << "str" << endl;
19     cin >> str;
20     size = str.size();
21     char *p = new char[size];
22     strcpy(p, str.c_str());
23     if (p[0] == '-') { p[0] = '0'; }//考虑到负数
24     for (i = 0; i < size; i++)
25     {
26         if (p[i] >= 'a'&&p[i] <= 'z')
27         {
28             p[i] = p[i] - 39;
29         }
30         if (p[i] >= 'A'&&p[i] <= 'Z')
31         {
32             p[i] = p[i] + 19;
33         }
34     }//将a-z的字符意义化a=10、···
35     for (i = 0; i < size; i++)
36     {
37         result += int(p[i] - 48) * int(pow(n1, size -
38 
39             1 - i));
40     }
41     cout << result << endl;//计算十进制值
42     while ((result / n2) >= n2)
43     {
44         r[n] = result % n2;
45         result = result / n2;
46         n++;
47     }
48     r[n] = result % n2;
49     n++;
50     r[n] = result / n2;//取余取除值
51     for (i = 0; i < (n + 1); i++)
52     {
53         if (r[i] >= 10&&r[i]<=35) { q[i] = r[i]+87; }//a-z的输出转换
54         else if (r[i] >=36&&r[i]<=61) { q[i] = r[i]+29; }//A-Z的输出转换
55         else { q[i] = char(r[i] + 48); }//0-9转换
56     }
57     if (p[0] == '0') { cout << "-"; }//负数还原
58     for (i = 0; i < (n + 1); i++)
59     {
60         cout << q[n - i];
61     }
62 }

结果如图:其中输出的第二行为10 进制的该数。

猜你喜欢

转载自www.cnblogs.com/ljy1227476113/p/9623660.html