1.题目描述
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进制
2.解题思路
- 按照十进制的加法方法,满36向前进一位
- 注意最后一次carry的值
3.代码实现
alphabet = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
def add_36(str1,str2):
len1 = len(str1)
len2 = len(str2)
i = len1 - 1
j = len2 - 1
res = ""
carry = 0
while i >= 0 and j >= 0:
s = alphabet.index(str1[i]) + alphabet.index(str2[j]) + carry
if s>=36:
carry = 1
res = alphabet[s%36] + res
else:
carry = 0
res = alphabet[s] + res
i -= 1
j -= 1
while i>=0:
s = alphabet.index(str1[i]) + carry
if s>=36:
carry = 1
res = alphabet[s%36] + res
else:
carry = 0
res = alphabet[s] + res
i -= 1
while j >= 0:
s = alphabet.index(str1[j]) + carry
if s >= 36:
carry = 1
res = alphabet[s % 36] + res
else:
carry = 0
res = alphabet[s] + res
j -= 1
if carry == 1:
res = "1" + res
print (res)
if __name__ == '__main__':
add_36("AB","Z")