Add Two Numbers

Description

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

给定两个非空链表表示的非负整数。实现加法,向后进位。

Solution

用一个int作进位寄存器,在下一位相加时加上进位寄存器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    head := &ListNode{}
    cur := head
    carry := 0

    for {
        var v1, v2 int
        if l1 != nil {
            v1 = l1.Val
            l1 = l1.Next
        }

        if l2 != nil {
            v2 = l2.Val
            l2 = l2.Next
        }

        v := v1 + v2 + carry

        carry = int(v / 10)
        cur.Val = v % 10

        if l1 != nil || l2 != nil {
            cur.Next = &ListNode{}
            cur = cur.Next
        } else {
            if carry > 0 {
                cur.Next = &ListNode{Val: carry}
            }

            break
        }
    }

    return head
}