Skip to content

2. 两数相加 #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jotoy opened this issue Feb 20, 2020 · 0 comments
Open

2. 两数相加 #27

jotoy opened this issue Feb 20, 2020 · 0 comments

Comments

@jotoy
Copy link
Owner

jotoy commented Feb 20, 2020

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

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

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

示例:

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

解法1:
直接按位操作。两个链表的起始端是个位,输出的链表起始端也是个位。因此可以考虑在读取2个链表节点时,直接将节点数值相加后赋值到新的链表中。由于两个数字相加后有可能产生越位,需要设置一个变量记录进位。具体实现如下:

# 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:
        phead = ListNode(None)
        p = phead
        m = 0
        while l1 or l2 or m==1:
            if l1:
                num1 = l1.val
                l1 = l1.next
            else: 
                num1 = 0
            if l2:
                num2 = l2.val
                l2 = l2.next
            else:
                num2 = 0
            p.next = ListNode((num1+num2+m)%10)
            if num1+num2+m>9:
                m = 1
            else:
                m = 0
            p = p.next
        return phead.next

解法2:
暴力法。先将链表转换成对应的数,将两数相加后重新整理为链表。不多介绍。

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        phead = ListNode(None)
        p = phead
        num1 = 0
        num2 = 0
        i = 0
        while l1:
            num1 = num1 + l1.val*10**i
            l1 = l1.next
            i+=1
        i = 0
        while l2:
            num2 = num2 + l2.val*10**i
            l2 = l2.next
            i+=1
        num3 = str(num1+num2)
        for i in range(len(num3)-1,-1,-1):
            p.next = ListNode(num3[i])
            p = p.next

        return(phead.next)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant