2. 两数相加

Posted leisurelylicht

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2. 两数相加相关的知识,希望对你有一定的参考价值。

  • Python3
# 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:
        l_result = ListNode(0)
        l_r = l_result
        carry = 0   
        while l1 or l2:
            x = l1.val if l1 else 0
            y = l2.val if l2 else 0
            
            result = x + y + carry
            carry = result // 10
            l_r.next = ListNode(result % 10)
            l_r = l_r.next
            
            if l1 is not None: l1 = l1.next
            if l2 is not None: l2 = l2.next
        
        if carry > 0:
            l_r.next = ListNode(carry)
            
        return l_result.next
  • Go
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    l_r := &ListNode{Val: 0}
    ptr := l_r
    carry := 0
    p := l1
    q := l2
    for (p != nil || q != nil) {
        x := 0
        if p != nil {
            x = p.Val
        }
        
        y := 0
        if q != nil {
            y = q.Val
        }
        
        sum := x + y + carry
        carry = sum / 10
        tmp := sum % 10
        
        ptr.Next = &ListNode{Val: tmp, Next: nil}
        ptr = ptr.Next
        
        if p != nil {
            p = p.Next
        }
        if q != nil {
            q = q.Next
        }
    }
    if carry > 0 {
        ptr.Next = &ListNode{Val: carry, Next: nil}
    }
    return l_r.Next
}

以上是关于2. 两数相加的主要内容,如果未能解决你的问题,请参考以下文章

代码题(11)— 链表两数相加

leetcode-2. 两数相加

LeetCode第2天 - 2. 两数相加

链表题--02----两数相加

LeetCode 2.两数相加

leetcode 算法题2 两数相加