leetcode-两数相加

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	if l1 == nil || l2 == nil{
		return nil
	}
	head := &ListNode{Val:0,Next:nil}
	current := head
	carry := 0
	for l1 !=nil || l2 != nil  {
		var x,y int
		if l1 == nil{
			x = 0
		}else {
			x = l1.Val
		}
		if l2 == nil{
			y = 0
		}else {
			y = l2.Val
		}
		current.Next = &ListNode{Val:(x+y+carry)%10, Next:nil}
		current = current.Next
		carry = (x+y+carry)/10

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

总结  carry代表进位,一位一位加即可,若其中一条链到底,均设置为0,直到两条都到底,结束,最后跳出循环再判断最后一位是否还有进位,有进位再添加一个节点记录。

欢迎留言