【LeetCode】2. 兩數相加(gloang)

package main

import (
	"fmt"
)

type ListNode struct {
	Val  int
	Next *ListNode
}

func main() {
	aList1 := &ListNode{Val: 1}
	bList1 := &ListNode{Val: 9}
	bList1.Next = &ListNode{Val: 9}
	cList := addTwoNumbers(aList1, bList1)
	fmt.Println(cList)
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	cList := &ListNode{}
	curr := cList
	first := l1
	second := l2
	//進位
	carry := 0
	for first != nil || second != nil {
		val1 := 0
		val2 := 0
		if first != nil {
			val1 = first.Val
		}
		if second != nil {
			val2 = second.Val
		}
		sum := carry + val1 + val2
		carry = sum / 10
		curr.Val = sum % 10
		if first != nil {
			first = first.Next
		}
		if second != nil {
			second = second.Next
		}
		if first != nil || second != nil {
			curr.Next = &ListNode{}
			curr = curr.Next
		}
	}
	if carry != 0 {
		curr.Next = &ListNode{Val: carry}
	}
	return cList
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章