【每日一题1206】奇怪的加法

:mage:t2: 请暂时忘掉曾经学过加法运算,今天,我们要尝试一个新的玩法:

运算规则:
image

请编写一个函数,接收2个数字,计算他们的加法和值。

题目难度:简单
题目来源:Codewars:16+18=214

def solution(num1: int, num2: int) -> int:
    # your code

assert solution(16, 18) == 214
assert solution(26, 39) == 515
assert solution(2, 11) == 13
def solution(num1: int, num2: int) -> int:

    num_list = []

    for i in range(min(len(str(num1)), len(str(num2)))):

        num_list.append(str(int(str(num1)[::-1][i]) + int(str(num2)[::-1][i])))

    if len(str(num1)) != len(str(num2)):

        num_list.append(str(max(num1, num2))[:len(str(max(num1, num2))) - len(str(min(num1, num2)))])

    return int(''.join(num_list[::-1]))

assert solution(16, 18) == 214

assert solution(26, 39) == 515

assert solution(2, 11) == 13
assert solution(122, 81) == 1103
def solution(num1: int, num2: int) -> int:
    maxLen = max(len(str(num1)),len(str(num2)))
    f = '{:0>'+ str(maxLen) +'d}'
    num1L = list(str(f.format(num1)))
    num2L = list(str(f.format(num2)))

    result = [str(int(num1L[i]) + int(num2L[i])) for i in range(maxLen)]
    return int(''.join(result))

assert solution(16, 18) == 214
assert solution(26, 39) == 515
assert solution(2, 11) == 13
def solution(num1: int, num2: int) -> int:
    result_str = ""
    max_len = len(str(max(num1,num2)))
    for i in range(max_len-1,-1,-1):
        caler = pow(10,i)
        result_str += str(num1//caler+num2//caler)
        num1 = num1 % caler
        num2 = num2 % caler
    return int(result_str)
assert solution(122, 81) == 1103

兄弟,你写的方法,这个过不了

1 个赞

现在可以了:grimacing:

1 个赞
def solution(m: int, n: int):
    if m<n:
        m,n = n,m

    def get_num_list(num):
        l = []
        while num>0:
            l.append(num%10)
            num = num//10
        return l
    l_m = get_num_list(m)
    l_n = get_num_list(n)
    l1 = []
    while len(l_m) and len(l_n):
        l1.insert(-1,l_m.pop(0)+l_n.pop(0))
    while len(l_m):
        l1.insert(0,l_m.pop(0))
    sum = 0
    i = 0
    while len(l1):
        q = l1.pop()
        sum+=q*10**i
        if q>=10:
            i+=2
        else:
            i+=1
    return sum
def solution(num1: int, num2: int) -> int:
    # your code
    result = []
    a = len(str(num1))
    b = len(str(num2))
    if a == b:
        for n in range(a):
            num = int(str(num1)[n]) + int(str(num2)[n])
            result.insert(0, str(num))
    elif a > b:
        for n in range(b):
            num = int(str(num1)[::-1][n]) + int(str(num2)[::-1][n])
            result.insert(len(result), str(num))
        result.insert(len(result), str(num1)[0:a-b])
    else:  # a < b
        for n in range(a):
            num = int(str(num1)[::-1][n]) + int(str(num2)[::-1][n])
            result.insert(len(result), str(num))
        result.insert(len(result), str(num2)[0:b - a])

    num0 = "".join(result[::-1])
    return int(num0)


assert solution(16, 18) == 214
assert solution(26, 39) == 515
assert solution(2, 11) == 13
assert solution(118, 23) == 1311
def solution(num1: int, num2: int) -> int:
    num = []
    count = 0
    minLen = min(num1, num2)
    min_l = len(str(minLen))
    maxLen = max(num1, num2)
    for i in str(maxLen)[::-1]:
        count += 1
        count1 = 0
        for j in str(minLen)[::-1]:
            if count1 == count - 1:
                num.append(str(int(i) + int(j)))
            count1 += 1
        if count > min_l:
            num.append(i)
    Num = ''.join(num[::-1])
    return int(Num)


if __name__ == '__main__':
    assert solution(16, 18) == 214
    assert solution(26, 39) == 515
    assert solution(2, 11) == 13

1 个赞
def solution(num1: int, num2: int) -> int:
    if len(str(num1))==len(str(num2)):
        return int(''.join(list(map(lambda x, y: str(x + y), [int(i) for i in str(num1)], [int(j) for j in str(num2)]))))
    elif len(str(num1))<len(str(num2)):
        new_num1='0'*(len(str(num2))-len(str(num1)))+str(num1)
        return int(''.join(list(map(lambda x, y: str(x + y), [int(i) for i in new_num1], [int(j) for j in str(num2)]))))
    else:
        new_num2='0'*(len(str(num1))-len(str(num2)))+str(num2)
        return int(''.join(list(map(lambda x, y: str(x + y), [int(i) for i in str(num1)], [int(j) for j in new_num2]))))



assert solution(16, 18) == 214
assert solution(26, 39) == 515
assert solution(2, 11) == 13
assert solution(122, 81) == 1103
def solution(num1: int, num2: int) -> int:
    temp_list = []
    while True:
        num1, rem1 = divmod(num1, 10)
        num2, rem2 = divmod(num2, 10)
        temp_list.insert(0, str(rem1 + rem2))
        if not num1 and not num2:
            break
    return int(''.join(temp_list))


assert solution(16, 18) == 214
assert solution(26, 39) == 515
assert solution(2, 11) == 13
assert solution(122, 81) == 1103

def solution(num1: int, num2: int) -> int:
    result = ""

    num1_str = str(num1)
    num2_str = str(num2)
    max_len = max(len(num1_str), len(num2_str))
    for i in range(0, max_len):
        get_num = lambda num_count: 0 if i + 1 > len(num_count) else int(num_count[0 - i - 1])
        num1_i = get_num(num1_str)
        num2_i = get_num(num2_str)
        result = str(num1_i + num2_i) + result
    return int(result)

Python 参考题解1

def solution(num1, num2):
    
    max_len = max([len(str(num1)), len(str(num2))])
    
    s1 = "{:0>{}d}".format(num1, max_len)
    s2 = f"%0{max_len}d" % num2
    
    result = list(map(lambda x,y: str(int(x)+int(y)), s1, s2))
    return int("".join(result))


assert solution(16, 18) == 214
assert solution(26, 39) == 515
assert solution(2, 11) == 13

思路:

  1. 对齐:先将两个可能长短不一的数字进行右对齐,左侧不足自动补充0

假设:solution(163, 18)
阶段成果示例:163, 018

  1. 计算:利用内置高级函数map,匿名函数定义映射的计算规则,使用列表推导式接收每个位置的和值。

阶段成果示例:['1', '7', '11']

  1. 拼接:利用str.join()方法拼接最终结果。

阶段成果示例:1711

Python参考题解2

from itertools import zip_longest

def solution(num1, num2):
    
    data = list(zip_longest(str(num1)[::-1], str(num2)[::-1]))
    data.reverse()
    
    result = [int(x[0] or 0) + int(x[1] or 0) for x in data]
    return int("".join([str(x) for x in result]))
    


assert solution(16, 18) == 214
assert solution(26, 39) == 515
assert solution(2, 11) == 13

思路:

  1. 映射:利用生成器函数zip_longest特点,先对输入进行翻转,然后对位映射,然后再翻转,从而实现了对位左侧不足补齐的效果。

假设:solution(163, 18)
阶段成果示例:[('1', None), ('6', '1'), ('3', '8')]

  1. 计算:遍历上一步的列表,计算每个元组的和值

阶段成果示例:[1, 7, 11]

  1. 拼接:将最终结果拼接成完整字符串。

阶段成果示例:1711

def solution(num1: int, num2: int) -> int:
    # 将整型转换为字符串后反转字符串
    num1_str = str(num1)[::-1]
    num2_str = str(num2)[::-1]
    # 取num1和num2的最小长度,用于2个转换后的字符串的每个元素相加
    l1 = min(len(num1_str), len(num2_str))
    sum_list = []
    for i in range(l1):
        sum_list.append(eval(num1_str[i]) + eval(num2_str[i]))
    # 将列表中的相加后的整数转为字符串
    sum_list_2 = [str(i) for i in sum_list]
    # 取num1和num2的最大长度,最大长度-最小长度,即为无需参加计算的字符
    l2 = max(len(num1_str), len(num2_str))
    if len(num1_str) > len(num2_str):
        sum_list_2.append(num1_str[l1:l2])
    elif len(num1_str) < len(num2_str):
        sum_list_2.append(num2_str[l1:l2])
    # 列表反转后,连接为字符串,再转为整型
    sum_list_2.reverse()
    return eval(''.join(sum_list_2))


assert solution(16, 18) == 214
assert solution(26, 39) == 515
assert solution(2, 11) == 13
def solution(num1, num2):
     count = max(len(str(num1)), len(str(num2)))

     if len(str(num1)) < count:
         num1 = str(num1).zfill(count)

     if len(str(num2)) < count:
         num2 = str(num2).zfill(count)
     
     new_tuple = list(zip(str(num1), str(num2)))
     result = [str(int(x[0]) + int(x[1])) for x in new_tuple]
     return int(''.join(result))
def test_add(num1: int, num2: int) -> int:
    max_list = list(str(max(num1, num2)))
    min_list = list(str(min(num1, num2)))
    for i in range(1, len(min_list)+1):
        max_list[-i] = str(int(min_list[-i])+int(max_list[-i]))
    return int(''.join(max_list))
def solution(num1: int, num2: int) -> int:
    li_num1 = list(str(num1))
    li_num2 = list(str(num2))
    over = len(li_num1)-len(li_num2)
    if over > 0 :
        li_num2.insert(0,0)
    elif over < 0:
        li_num1.insert(0,0)
    return int("".join([str(int(li_num1[i])+int(li_num2[i])) for i in range(len(li_num1))]))


assert solution(16, 18) == 214
assert solution(26, 39) == 515
assert solution(2, 11) == 13
assert solution(122, 81) == 1103