LeetCode题解(Golang实现)--Add Two Numbers
发布时间:2020-12-16 18:06:53 所属栏目:大数据 来源:网络整理
导读:题目 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
题目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) 解题思路这题其实很简单,就是两个数字相加,只是把这两个数字用两个链表表示,进行两个链表相加 实现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
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |