算法题目 Python

本文介绍了如何使用Python实现一个名为`Solution`的类,用于将两个字符串(例如1LC415进制下的数字)进行相加,通过`getInt`和`getChar`函数将字符转换为整数和回字符。最终给出了`addStrings`函数的具体实现和一个示例输出。
摘要由CSDN通过智能技术生成

记录有意思的算法题, 大都不是自己写的,学习一下  >_<

字符串

1 LC415 字符串相加

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        res = ""
        i, j = len(num1) - 1, len(num2) - 1
        carry = 0 #进位
        while i >= 0 or j >= 0:
            if i < 0:
                n1 = 0
            else:
                n1 = int(num1[i])
            if j < 0:
                n2 = 0
            else:
                n2 = int(num2[j])
            tmp = n1 + n2 + carry
            carry = tmp // 10
            res = str(tmp % 10) + res
            i -= 1
            j -= 1
        return "1" + res if carry else res

2 36进制加法

和上题代码一样。

def getInt(x):
    if '0' <= x <= '9':
        x_int = int(x)
    else:
        x_int = ord(x) - ord('a') + 10
    return x_int

def getChar(x):
    if x <= 9:
        x_char = str(x)
    else:
        x_char = chr(x - 10 + ord('a'))
    return x_char
def addStrings(num1, num2):
    res = ""
    i, j = len(num1) - 1, len(num2) - 1
    carry = 0 #进位
    while i >= 0 or j >= 0:
        if i < 0:
            n1 = 0
        else:
            n1 = getInt(num1[i])
        if j < 0:
            n2 = 0
        else:
            n2 = getInt(num2[j])
        tmp = n1 + n2 + carry
        carry = tmp // 36
        res = getChar(tmp % 36) + res
        i -= 1
        j -= 1
    return "1" + res if carry else res

print(addStrings("1b" , "2x"))

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值