码迷,mamicode.com
首页 > 编程语言 > 详细

golang 算法题 : 两数相加

时间:2019-05-11 23:08:03      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:family   golang   imp   print   pre   ber   type   size   return   

package main

import "fmt"

type ListNode struct {
Val int
Next *ListNode
}

func main() {
l1 := &ListNode{
Val: 1,
Next: &ListNode{
Val: 2,
Next: &ListNode{
Val: 3,
},
},
}
l2 := &ListNode{
Val: 4,
Next: &ListNode{
Val: 5,
Next: &ListNode{
Val: 6,
},
},
}
l3 := addTwoNumbers(l1, l2)
num := ""
for l3 != nil {
val := l3.Val
num = fmt.Sprintf("%s%d", num, val)
l3 = l3.Next
}
fmt.Println(num)
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var head *ListNode
var previous *ListNode
var current *ListNode
var carry int
for l1 != nil || l2 != nil {
v1 := 0
v2 := 0
if l1 != nil {
v1 = l1.Val
}
if l2 != nil {
v2 = l2.Val
}
result := v1 + v2 + carry
nodeVal := result % 10
carry = result / 10
current = &ListNode{
Val: nodeVal,
}
if head == nil {
head = current
}
if previous != nil {
previous.Next = current
}

previous = current

if l1 != nil {
l1 = l1.Next
}
if l2 != nil {
l2 = l2.Next
}

}

if carry > 0 {
current = &ListNode{
Val: carry,
}
if head == nil {
head = current
}
if previous != nil {
previous.Next = current
}
}

return head
}

golang 算法题 : 两数相加

标签:family   golang   imp   print   pre   ber   type   size   return   

原文地址:https://www.cnblogs.com/w3liu/p/10850325.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!