您的位置:首页 > 编程语言 > Go语言

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

2017-08-28 16:34 381 查看

题目

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
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  numbers leetcode golang