2.两数相加(中等)

 

两数相加

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

 最新方案(2019年 12月 25日 星期三 11:09:49 CST)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
def panduan_val(x):
        if x==None:
            return 0
        else:
            return x.val

class Solution:

    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        #定义sum链表
        lsum_hand =ListNode(0)
        lsum =lsum_hand
        l1_now =l1
        l2_now =l2
#hand
        #赋值
        lsum_jinyi =(panduan_val(l1_now)+panduan_val(l2_now))//10
        lsum.val=(panduan_val(l1_now)+panduan_val(l2_now))%10
        #判断next有无意义       
        l1_now=l1_now.next if (l1_now!=None and l1_now.next!=None) else None 
        l2_now=l2_now.next if (l2_now!=None and l2_now.next!=None) else None
 #others
        while((l1_now!=None) or (l2_now!=None) or lsum_jinyi==1):
            #定义新节点
            lsum.next=ListNode(0)
            lsum=lsum.next
            #赋值
            lsum.val = lsum_jinyi
            lsum.val += panduan_val(l1_now)+panduan_val(l2_now)
            lsum_jinyi = lsum.val//10
            lsum.val = lsum.val%10
            #判断next有无意义
            l1_now=l1_now.next if (l1_now!=None and l1_now.next!=None) else None 
            l2_now=l2_now.next if (l2_now!=None and l2_now.next!=None) else None
        return lsum_hand

原始方案

利用链表硬求(自己写的,很垃圾)

思想正确,代码待优化

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        l3=ListNode(0)
        l3_next_v=0
        l0=l3
        if1=0
        if2=0
        count = 0 
        while(1):
            l3_next=ListNode(l3_next_v)
            if l1 ==None and l2 ==None:
                if l3_next_v ==1 :
                    l3_next=ListNode(l3_next_v)
                    l3.next = l3_next
                    l3=l3.next                     
                #print (2)
                break            
            elif l1 ==None:
                #print (12)
                tianchong(l2,l3,l3_next_v)
                break
            elif l2 ==None:
                #print (13)
                tianchong(l1,l3,l3_next_v)
                break
            if count != 0:
                
                #print (1234)
                l3_next=ListNode(l3_next_v)
                l3.next = l3_next
                l3=l3.next      
                
            v1 = l1.val
            l1 = l1.next
            v2 = l2.val
            l2 = l2.next
            t3 = l3.val+v1+v2
            l3.val = (t3)%10
            l3_next_v = (t3)//10
 #print ('1',l3.val)
            print ('l3',l3_next_v)
            count +=1
        
        return l0

def tianchong(x,y,t):
    y.next = ListNode(t)
    y = y.next
    count = 0
    y_next_v=0
    while(1):
        if x == None:
            if(y_next_v == 1):
                #print (y_next_v);
                y.next = y_next
                y=y.next
            #print ('1')
            break
        elif count != 0:
            y.next = y_next
            y = y.next
        y_next_v = (y.val+x.val)//10
        y.val = (y.val+x.val)%10
        y_next = ListNode(y_next_v)
        x = x.next
        count += 1

 完整代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        l3=ListNode(0)
        l3_next_v=0
        l0=l3
        if1=0
        if2=0
        count = 0 
        while(1):
            l3_next=ListNode(l3_next_v)
            if l1 ==None and l2 ==None:
                if l3_next_v ==1 :
                    l3_next=ListNode(l3_next_v)
                    l3.next = l3_next
                    l3=l3.next                     
                #print (2)
                break            
            elif l1 ==None:
                #print (12)
                tianchong(l2,l3,l3_next_v)
                break
            elif l2 ==None:
                #print (13)
                tianchong(l1,l3,l3_next_v)
                break
            if count != 0:
                
                #print (1234)
                l3_next=ListNode(l3_next_v)
                l3.next = l3_next
                l3=l3.next      
                
            v1 = l1.val
            l1 = l1.next
            v2 = l2.val
            l2 = l2.next
            t3 = l3.val+v1+v2
            l3.val = (t3)%10
            l3_next_v = (t3)//10
 #print ('1',l3.val)
            print ('l3',l3_next_v)
            count +=1
        
        return l0

def tianchong(x,y,t):
    y.next = ListNode(t)
    y = y.next
    count = 0
    y_next_v=0
    while(1):
        if x == None:
            if(y_next_v == 1):
                #print (y_next_v);
                y.next = y_next
                y=y.next
            #print ('1')
            break
        elif count != 0:
            y.next = y_next
            y = y.next
        y_next_v = (y.val+x.val)//10
        y.val = (y.val+x.val)%10
        y_next = ListNode(y_next_v)
        x = x.next
        count += 1

def stringToIntegerList(input):
    return json.loads(input)

def stringToListNode(input):
    # Generate list from the input
    numbers = stringToIntegerList(input)

    # Now convert that list into linked list
    dummyRoot = ListNode(0)
    ptr = dummyRoot
    for number in numbers:
        ptr.next = ListNode(number)
        ptr = ptr.next

    ptr = dummyRoot.next
    return ptr

def listNodeToString(node):
    if not node:
        return "[]"

    result = ""
    while node:
        result += str(node.val) + ", "
        node = node.next
    return "[" + result[:-2] + "]"

def main():
    import sys
    import io
    def readlines():
        for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)
            l1 = stringToListNode(line);
            line = next(lines)
            l2 = stringToListNode(line);
            
            ret = Solution().addTwoNumbers(l1, l2)

            out = listNodeToString(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()

 1.2参考大佬的代码

精彩:while val  or l1 or l2

用了很多 同行的 a if  条件 else b,使代码简洁了很多。 

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        prenode = ListNode(0)
        lastnode = prenode
        val = 0
        while val or l1 or l2:
            val, cur = divmod(val + (l1.val if l1 else 0) + (l2.val if l2 else 0), 10)
            lastnode.next = ListNode(cur)
            lastnode = lastnode.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return prenode.next


def generateList(l: list) -> ListNode:
    prenode = ListNode(0)
    lastnode = prenode
    for val in l:
        lastnode.next = ListNode(val)
        lastnode = lastnode.next
    return prenode.next

def printList(l: ListNode):
    while l:
        print("%d, " %(l.val), end = '')
        l = l.next
    print('')

if __name__ == "__main__":
    l1 = generateList([1, 5, 8])
    l2 = generateList([9, 1, 2, 9])
    printList(l1)
    printList(l2)
    s = Solution()
    sum = s.addTwoNumbers(l1, l2)
    printList(sum)

作者:xiao-lin-20
链接:https://leetcode-cn.com/problems/add-two-numbers/solution/cjie-ti-de-wan-zheng-dai-ma-bao-gua-sheng-cheng-ce/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

第二种方案

把链表中的数字移到列表中,待求出后,再转移到新的链表中。

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummyHead = ListNode(0)
        curr, carry = dummyHead, 0
        while l1 or l2:
            sum = 0
            if l1:
                sum += l1.val
                l1 = l1.next
            if l2:
                sum += l2.val
                l2 = l2.next
            sum += carry
            carry = sum // 10
            curr.next = ListNode(sum % 10)
            curr = curr.next
        if carry > 0:
            curr.next = ListNode(1)
        return dummyHead.next;

作者:jimmy00745
链接:https://leetcode-cn.com/problems/add-two-numbers/solution/guan-fang-ti-jie-de-python3-c-shi-xian-by-jimmy007/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值