[6 kyu] Sum two arrays

[6 kyu] Sum two arrays

Question

在这里插入图片描述

Sample Tests

在这里插入图片描述

My answer (accepted)

def sum_arrays(array1,array2):
    print(array1)
    print(array2)
    if not array1:
        return array2
    if not array2:
        return array1
    if not array1 and not array2:
        return []
    if array1 == array2 == [0]:
        return []
    else:
        array1_n = [str(i) for i in array1]
        array2_n = [str(i) for i in array2]
        ans = int("".join(array1_n)) + int("".join(array2_n))
        string_num = list(str(ans))
        # ['-','1','2']
        new_string_num = []
        print(string_num)
        if string_num[0] == "-":
            first_item = string_num[0] + string_num[1]
            new_string_num.append(first_item)
            for i in range(2,len(string_num)):
                new_string_num.append(string_num[i])
        else:
            new_string_num = string_num
        return [int(i) for i in new_string_num]

Suggested answer

def sum_arrays(ar1,ar2):
    answ = []
    if not ar1 and not ar2: return []
    if not ar1: return ar2
    if not ar2: return ar1
    if ar1[0] == 0 and ar2[0] == 0 : return []
    sa1 = "".join([str(k) for k in ar1])
    sa2 = "".join([str(j) for j in ar2])
    r = int(sa1) + int(sa2)
    if str(r)[0] == '-':
        for s in str(r)[1:]:
            answ.append(int(s))
        answ[0] *= -1
        return answ
    for s in str(r):
        answ.append(int(s))
    return answ
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

panzhong171

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值