原题链接:PTA | 程序设计类实验辅助教学平台
Tips:以下Python代码仅个人理解,非最优算法,仅供参考!多学习其他大佬的AC代码!
def add_base30(num1, num2):
max_length = max(len(num1), len(num2))
# 在前面补零,使两个字符串长度相同
num1 = num1.zfill(max_length)
num2 = num2.zfill(max_length)
carry = 0
result = []
for i in range(max_length - 1, -1, -1):
if '0' <= num1[i] <= '9':
value1 = int(num1[i]) # 0-9
else:
value1 = ord(num1[i]) - ord('a') + 10 # a-t对应10-29
if '0' <= num2[i] <= '9':
value2 = int(num2[i]) # 0-9
else:
value2 = ord(num2[i]) - ord('a') + 10 # a-t对应10-29
# 计算当前位的和
total = value1 + value2 + carry
carry = total // 30
remainder = total % 30
# 根据余数将结果字符添加到结果列表中
if remainder < 10:
result.append(str(remainder))
else:
result.append(chr(remainder - 10 + ord('a')))
# 如果还有进位,则需要加到结果中
if carry > 0:
if carry < 10:
result.append(str(carry))
else:
result.append(chr(carry - 10 + ord('a')))
# 由于结果是反向构建的,因此反转
result.reverse()
# 连接为字符串并返回,测试点3:并去掉前导0
result_str = ''.join(result).lstrip('0')
# 处理特殊情况:测试点3,如果结果为空字符串,表示结果为0
return result_str if result_str else '0'
def main():
# 读取输入
num1, num2 = input().strip().split()
# 计算和
result = add_base30(num1, num2)
print(result)
if __name__ == "__main__":
main()
标签:__,num1,num2,Python,max,钱串子,1113,result,carry
From: https://blog.csdn.net/m0_56677113/article/details/142961323