字节跳动面试题.36进制加法

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")



 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值