P1604 B进制星球

题目链接

https://www.luogu.org/problemnew/show/P1604

题目背景

进制题目,而且还是个计算器~~

题目描述

话说有一天,小Z乘坐宇宙飞船,飞到一个美丽的星球。因为历史的原因,科技在这个美丽的星球上并不很发达,星球上人们普遍采用B(2<=B<=36)进制计数。星球上的人们用美味的食物招待了小Z,作为回报,小Z希望送一个能够完成B进制加法的计算器给他们。 现在小Z希望你可以帮助他,编写实现B进制加法的程序。

输入输出格式

输入格式:

共3行第1行:一个十进制的整数,表示进制B。第2-3行:每行一个B进制数正整数。数字的每一位属于{0,1,2,3,4,5,6,7,8,9,A,B……},每个数字长度<=2000位。

输出格式:

一个B进制数,表示输入的两个数的和。

输入输出样例

输入样例#1: 
4
123
321
输出样例#1:
1110

说明

进制计算器

题目分析

看到题目就很显然的得知

此题为高精度+进制转换

将B进制转化成十进制后求和

然后再将十进制下的和转换成B进制即可

然而这种水题我没有一遍过

PS:在判断前导0时应该用int的数组判断,因为char的数组中“0”对应的ASCLL码非零!也可以用char的数组和'0'(即0的ASCLL)比较

参考代码

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cctype>
 5 
 6 using namespace std;
 7 //#define DEBUG(x) cerr << #x << "=" << x << endl
 8 const int maxn = 1e6 + 10;
 9 
10 int base, i, len1, len2, len;
11 int cur = 0, first = 1, jw;
12 int a[maxn], b[maxn], sum[maxn];
13 char s1[maxn], s2[maxn], sum_s[maxn];
14 
15 inline int read()
16 {
17     char ch, c;
18     int res;
19     while (ch = getchar(), ch < '0' || ch > '9') c = ch;
20     res = ch - 48;
21     while (ch = getchar(), ch >= '0' && ch <= '9')
22     res = res * 10 + ch - 48;
23     if (c == '-') res = -res;
24     return res;
25 }
26 
27 void write(int x)
28 {
29     if (x < 0) putchar('-'), x = -x;
30     if (x > 9) write(x / 10);
31     putchar(x % 10 + '0');
32     return;
33 }
34 
35 int max(int x, int y)
36 {
37     return x > y ? x : y;
38 }
39 
40 int main()
41 {
42     ios::sync_with_stdio(false);
43     cin.tie(0);
44     cin >> base;
45     cin >> s1;
46     cin >> s2;
47     len1 = strlen(s1);
48     len2 = strlen(s2);
49     for (int i = len1 - 1; i >= 0; i--)
50     {
51         if (isalpha(s1[i])) a[++cur] = s1[i] - 'A' + 10;
52         else a[++cur] = s1[i] - '0';
53     }
54     cur = 0;
55     for (int i = len2 - 1; i >= 0; i--)
56     {
57         if (isalpha(s2[i])) b[++cur] = s2[i] - 'A' + 10;
58         else b[++cur] = s2[i] - '0';
59     }
60     len = max(len1, len2) + 1;
61     for (int i = 1; i <= len; i++)
62     {
63         sum[i] = (a[i] + b[i] + jw) % base;
64         jw = (a[i] + b[i] + jw) / base;
65     }
66     for (int i = 1; i <= len; i++)
67         if (sum[i] > 9) sum_s[i] = sum[i] - 10 + 'A';
68         else sum_s[i] = sum[i] + '0';
69     for (int i = len; i >= 1; i--)
70         if (first && !sum[i]) continue;
71         else
72         {
73             first = 0;
74             cout << sum_s[i];
75         }
76     puts("");
77     return 0;
78 }
原文地址:https://www.cnblogs.com/aiyi2000/p/9808371.html