leetcode--(2. Add Two Numbers)
Posted 孤独风中一匹狼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode--(2. 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
翻译:对两个单向链表求和,链表头为低位,链表尾是高位
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { var l3 =&ListNode{} q:=l3 c:=0 for l1!=nil&&l2!=nil{ p:=&ListNode{} sum:=l1.Val+l2.Val+c p.Val=sum%10 q.Next=p q=p c=sum/10 l1=l1.Next l2=l2.Next } for l1!=nil{ p:=&ListNode{} sum:=l1.Val+c p.Val=sum%10 q.Next=p q=p c=sum/10 l1=l1.Next } for l2!=nil{ p:=&ListNode{} sum:=l2.Val+c p.Val=sum%10 q.Next=p q=p c=sum/10 l2=l2.Next } for c>0{ p:=&ListNode{} p.Val=c%10 c=c/10 q.Next=p q=p } return l3.Next }
以上是关于leetcode--(2. Add Two Numbers)的主要内容,如果未能解决你的问题,请参考以下文章
2. 两个数相加 [leetcode 2: Add Two Numbers]
2. 两个数相加 [leetcode 2: Add Two Numbers]