LeetCode题解(Golang实现)–Add Two Numbers

  • Post author:
  • Post category:golang


题目

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

解题思路

这题其实很简单,就是两个数字相加,只是把这两个数字用两个链表表示,进行两个链表相加

实现

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    head := &ListNode{0, nil}
    current := head
    carry := 0
    for l1 != nil || l2 != nil || carry > 0 {
        sum := carry
        if l1 != nil {
            sum += l1.Val
            l1 = l1.Next
        }
        if l2 != nil {
            sum += l2.Val
            l2 = l2.Next
        }
        carry = sum / 10
        current.Next = new(ListNode)
        current.Next.Val = sum % 10
        current = current.Next
    }
    return head.Next
}



版权声明:本文为a32521500原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。