leetcode 第2题-两数相加

输入:l1 = [2,4,3], l2 = [5,6,4]输出:[7,0,8]解释:342 + 465 = 807.

输入:l1 = [0], l2 = [0]输出:[0]

输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]输出:[8,9,9,9,0,0,0,1]

func AddTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    node := new(ListNode)
    head := node
    incr := 0
    //链表不为空或者进位的数不为0都要继续遍历
    for l1 != nil || l2 != nil || incr > 0 {
        value1 := 0
        value2 := 0
        if l1 != nil {
            value1 = l1.Val
            l1 = l1.Next
        }
        if l2 != nil {
            value2 = l2.Val
            l2 = l2.Next
        }

        sum := value1 + value2 + incr
        if sum >= 10 {
            sum = sum - 10
            incr = 1
        } else {
            incr = 0
        }
        tmp := new(ListNode)
        tmp.Val = sum
        tmp.Next = nil
        node.Next = tmp
        node = tmp
    }

    return head.Next
}

你可能感兴趣的:(leetcode 第2题-两数相加)