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

前端之家收集整理的这篇文章主要介绍了LeetCode题解(Golang实现)--Add Two Numbers前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

题目

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
}

猜你在找的Go相关文章