Fork me on GitHub

三十六进制加法

问题描述
36进制由0-9,a-z,共36个字符表示,最小为’0’。 ‘0’、’9’对应十进制的0、9,‘a’、’z’对应十进制的10、35

例如:

‘1b’ 换算成10进制等于 1 36^1 + 11 36^0 = 36 + 11 = 47
要求按照加法规则计算出任意两个36进制正整数的和
如:按照加法规则,计算’1b’ + ‘2x’ = ‘48’

要求:
不允许把36进制数字整体转为10进制数字,计算出10进制数字的相加结果再转回为36进制

思路
按照十进制的加法方法,满36向前进一位

C++实现代码:

36hex_calculation.cpplink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*=============================================================================
# Author: Hailin - https://fuhailin.github.io/
# Email: hailinfufu@outlook.com
# Description: 三十六进制加法
=============================================================================*/


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

string add(const int &m, string a, string b)
{
int len1 = a.length(), len2 = b.length(), len = 0;
if (len1 > len2)
{
len = len1;
int temp = len1 - len2;
b.insert(0, temp, '0');
}
else if (len2 > len1)
{
len = len2;
int temp = len2 - len1;
a.insert(0, temp, '0');
}
else
{
len = len1;
}
string sum;
int remainder = 0, carry = 0;
for (int i = len - 1; i >= 0; i--)
{
int one1 = a[i];
int two1 = b[i];
if (a[i] > '9')
{
one1 = a[i] - 'a' + 10;
}
else
{
one1 = a[i] - '0';
}
if (b[i] > '9')
{
two1 = b[i] - 'a' + 10;
}
else
{
two1 = b[i] - '0';
}
int temp = one1 + two1 + carry;
remainder = temp % m;
carry = temp / m;
if (remainder > 9)
{
char ctemp = remainder + 'a' - 10;
sum = sum + ctemp;
}
else
{
char ctemp = remainder + '0';
sum = sum + ctemp;
}
}
if (carry)
{
char ctemp = '0' + carry;
sum = ctemp + sum;
}
return sum;
}

int main()
{
int hex;
string a, b;
cin >> hex >> a >> b;
string res = add(hex, a, b);
cout << a << " + " << b << " = " << res;
return 0;
}

您的支持将鼓励我继续创作!
0%