美文网首页
go语言解leetcode习题 2. Add Two Numbe

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

作者: 倒数第三 | 来源:发表于2017-06-12 17:29 被阅读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
    }

    相关文章

      网友评论

          本文标题:go语言解leetcode习题 2. Add Two Numbe

          本文链接:https://www.haomeiwen.com/subject/rwnlqxtx.html