Add two numbers - force button

1 question

You are given two non-empty linked lists, representing two non-negative integers. Each of their digits is stored in reverse order, and each node can only store one digit.

Please add two numbers and return a linked list representing the sum in the same form.

You can assume that except for the number 0, neither number will start with a 0.
Insert image description here

输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.

Example 2:

输入:l1 = [0], l2 = [0]
输出:[0]

Example 3:

输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]

2 answers

I added a comment above the original link

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    
    
    carry:=0//判断是否要进位
    w:=0//用来承接sum的取余
    sum:=0
    head:=&ListNode{
    
    Val:0}//创建一个空的链表
    prev:=head
    for l2 != nil&&l1 != nil  {
    
    
        sum = l1.Val+l2.Val+carry
        w=sum%10//得余数
        carry=sum/10//判断是否进位,得整数
        prev.Next = &ListNode{
    
    Val:w}//把余数存入链表
        prev = prev.Next
        l1 = l1.Next
        l2 = l2.Next
        //fmt.Println(carry)
    }
    if l2==nil {
    
    
        l2 = l1
    }

    for l2!=nil||carry != 0 {
    
    //进行的是L2的自己相加,carry只进行一次,直到L2为nil时结束循环
        x:=0
        if l2!=nil{
    
    
            x=l2.Val
            l2 = l2.Next
        }
        sum = x+carry
        w= sum%10
        carry = sum/10
        prev.Next = &ListNode{
    
    Val:w}
        prev = prev.Next
    }
    return head.Next
}

3Related links

https://zhuanlan.zhihu.com/p/111049347
Source: LeetCode
Link: https://leetcode-cn.com/problems/add-two-numbers

Guess you like

Origin blog.csdn.net/weixin_42375493/article/details/122072461