# 2.两数相加 golang

``````/**
* type ListNode struct {
*     Val int
*     Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
sum := l1.Val + l2.Val
jw := sum/10
sum = sum%10
val1 := 0
val2 := 0
l1 = l1.Next
l2 = l2.Next
for l1 != nil || l2 != nil || jw != 0 {
if l1 == nil {
val1 = 0
} else {
val1 = l1.Val
l1 = l1.Next
}
if l2 == nil {
val2 = 0
} else {
val2 = l2.Val
l2 = l2.Next
}
sum = val1 + val2 + jw
jw = sum/10
sum = sum%10
tmp.Next = &ListNode{sum,nil}
tmp = tmp.Next
}
}
``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传
``````/**
* type ListNode struct {
*     Val int
*     Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
sum := l1.Val + l2.Val
jw := sum/10
sum = sum%10
val1 := 0
val2 := 0
l1 = l1.Next
l2 = l2.Next
for l1 != nil || l2 != nil || jw != 0 {
if l1 == nil {
val1 = 0
} else {
val1 = l1.Val
l1 = l1.Next
}
if l2 == nil {
val2 = 0
} else {
val2 = l2.Val
l2 = l2.Next
}
sum = val1 + val2 + jw
jw = sum/10
sum = sum%10
tmp.Next = &ListNode{sum,nil}
tmp = tmp.Next
}