go语言解leetcode习题 2. Add Two Numbe

2017-06-12  本文已影响0人  倒数第三

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
大数相加问题,给定两个链表,返回其相加和。注意:位数是从低到高 既2->4->3代表342

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    var a ListNode
    b := new(ListNode)
    carry := 0
    i := 0
    for {
        b.Val = (l1.Val + l2.Val + carry) % 10
        carry = (l1.Val + l2.Val + carry) / 10
        if l1.Next == nil && l2.Next == nil && carry == 0 {
            break
        }
        if l1.Next != nil {
            l1 = l1.Next
        } else {
            l1.Val = 0
            l1.Next = nil
        }
        if l2.Next != nil {
            l2 = l2.Next
        } else {
            l2.Val = 0
            l2.Next = nil
        }
        b.Next = new(ListNode)
        if i == 0 {
            a.Next = b.Next
        }
        b = b.Next
        i++
    }
    return &a
}
上一篇下一篇

猜你喜欢

热点阅读