2. Add Two Numbers

该博客讨论了如何解决将两个逆序存储在链表中的非负整数相加的问题。博主首先尝试直接将链表数字相加,然后意识到逐位计算并处理进位是更好的方法。解决方案涉及迭代链表,处理不同长度和进位,并提供了一个时间复杂度为O(max(m,n)),空间复杂度为O(max(m,n))的算法。博主还提到了非逆序存储的链表相加会增加问题难度。" 49254233,5535747,使用EasySQLMAIL进行Oracle订单异常监控与邮件发送,"['数据库', 'Oracle', '邮件服务', '数据监控', '自动化']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

My Solution:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        boolean carry = false;
        ListNode result = new ListNode(0);
        ListNode p = result;
        while(l1 != null || l2 != null){
        	int s = 0;
        	if(carry == true) {
        		s = 1;
        		carry = false;
        	}
            int a = l1 == null ? 0 : l1.val;
            int b = l2 == null ? 0 : l2.val;
            s += a + b;
            if(s >= 10) {
            	carry = true;
            	s %= 10;
            }
            p.next = new ListNode(s);
            p = p.next;
            if(l1 !=null)
            	l1 = l1.next;
            if(l2 !=null)
            	l2 = l2.next;
        }
        if(carry) {
        	p.next = new ListNode(1);
        }
        return result.next;
    }
}

Solution:

Intuition

Keep track of the carry using a variable and simulate digits-by-digits sum starting from the head of list, which contains the least-significant digit.

Illustration of Adding two numbers

Figure 1. Visualization of the addition of two numbers: 342 + 465 = 807.
Each node contains a single digit and the digits are stored in reverse order.

Algorithm

Just like how you would sum two numbers on a piece of paper, we begin by summing the least-significant digits, which is the head of l1 and l2. Since each digit is in the range of 09, summing two digits may "overflow". For example 5 + 7 = 12. In this case, we set the current digit to 2 and bring over the carry = 1 to the next iteration. carry must be either 0 or 1 because the largest possible sum of two digits (including the carry) is 9 + 9 + 1 = 19

The pseudocode is as following:

  • Initialize current node to dummy head of the returning list.
  • Initialize carry to 00.
  • Initialize p and q to head of l1 and l2 respectively.
  • Loop through lists l1 and l2 until you reach both ends.
    • Set xx to node p's value. If p has reached the end of l1, set to 00.
    • Set yy to node q's value. If q has reached the end of l2, set to 00.
    • Set sum = x + y + carry.
    • Update carry = sum / 10.
    • Create a new node with the digit value of (sum mod 10) and set it to current node's next, then advance current node to next.
    • Advance both p and q.
  • Check if carry = 1, if so append a new node with digit 1 to the returning list.
  • Return dummy head's next node.

Note that we use a dummy head to simplify the code. Without a dummy head, you would have to write extra conditional statements to initialize the head's value.

Take extra caution of the following cases:

Test caseExplanation
l1=[0,1]
l2=[0,1,2]
When one list is longer than the other.
l1=[]
l2=[0,1]
When one list is null, which means an empty list.
l1=[9,9]
l2=[1]

The sum could have an extra carry of one at the end, which is easy to forget.


public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    int carry = 0;
    while (p != null || q != null) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;
}
Complexity Analysis
  • Time complexity :O(max(m,n)). Assume that m and n represents the length of l1 and l2 respectively, the algorithm above iterates at most max(m,n) times.

  • Space complexity : O(max(m,n)). The length of the new list is at most max(m,n)+1.

Follow up

What if the the digits in the linked list are stored in non-reversed order? For example:

(342)+(465)=807


Summary:

本题一开始我的思路是将两个链表里的数相加,再逐位存入链表。但很明显这种方法是不好的,很容易导致溢出等错误。

此类题目应该进行逐位的运算,判断是否进位,再进行下一位的运算。需要注意的是两个数字可能位数不一样,此时需要补零进行计算。对于链表的结构和运用还不够了解。

此外,由于本题数字是反转后存入链表的,存储的顺序恰好和计算的顺序一致,若不反转则难度又提升了。相关习题:445. Add Two Numbers II。

<think>好的,我现在需要解决用户提出的Python错误:TypeError: Solution.addTwoNumbers() takes 2 positional arguments but 3 were given。首先,我要分析这个错误的原因。根据用户提供的引用资料,这类错误通常与类方法的参数数量不匹配有关。特别是当调用实例方法时,Python会自动将实例本身作为第一个参数(通常命名为self)传递,所以方法定义时需要包含self参数。 用户提到在Solution类中的addTwoNumbers方法出现了这个问题。可能的情况是,用户定义方法时没有包含self作为第一个参数,导致在调用时传递了多余的参数。例如,如果定义方法时写成了def addTwoNumbers(a, b):,而实际调用时使用了instance.addTwoNumbers(a, b, c),这时会因为缺少self参数而出现参数数量不匹配的错误。 接下来,我需要验证这个假设是否正确。查看用户提供的错误信息,错误提示说有3个参数被传入,但方法只接受2个。这说明在调用时确实传递了三个参数,而方法定义中只声明了两个参数。结合类方法的特点,正确的定义应该包含self作为第一个参数,然后是用户需要的参数。例如,正确的方法定义应该是def addTwoNumbers(self, a, b):,这样在实例调用时,参数数量才会匹配。 然后,我需要考虑可能的解决方案。根据引用[2]和[4]中的建议,解决方法包括检查方法定义是否包含self参数,或者在调用时是否错误地传递了多余的参数。在这种情况下,用户的问题很可能是方法定义缺少self参数,导致调用时自动传递的self加上用户参数,总数超过了预期。 最后,我需要将这些分析整理成步骤清晰的解决方案,并生成相关问题,帮助用户进一步理解和避免类似错误。</think>### 解决方案 Python类方法中出现`TypeError: addTwoNumbers takes 2 positional arguments but 3 were given`的根本原因是**类方法定义缺少`self`参数**,或调用方式错误导致参数数量不匹配。以下是具体分析及解决方法: --- #### **错误原因分析** 1. **缺少`self`参数** 在类中定义实例方法时,第一个参数必须为`self`(表示类实例自身)。如果未显式声明`self`,调用时会因自动传入`self`而导致参数数量错误。 **错误示例**: ```python class Solution: def addTwoNumbers(a, b): # 缺少self参数 return a + b ``` 调用`Solution().addTwoNumbers(2,3)`时,实际传递的参数是`(self, 2, 3)`,导致参数数量为3,但方法定义只接受2个参数。 2. **调用方式错误** 若将实例方法当作静态方法调用(例如通过类名直接调用),也会因缺少`self`参数导致错误。 --- #### **解决方法** 1. **在方法定义中显式添加`self`参数** 修改方法定义,将第一个参数设为`self`: ```python class Solution: def addTwoNumbers(self, a, b): # 正确添加self参数 return a + b ``` 2. **正确调用实例方法** 通过类实例调用方法,Python会自动传递`self`参数: ```python s = Solution() result = s.addTwoNumbers(2, 3) # 正确调用 ``` 3. **使用`@staticmethod`装饰器(可选)** 如果方法不需要访问类实例属性,可声明为静态方法: ```python class Solution: @staticmethod def addTwoNumbers(a, b): # 无需self参数 return a + b ``` 调用方式:`Solution.addTwoNumbers(2, 3)`[^4] --- #### **完整修复示例** ```python class Solution: def addTwoNumbers(self, a, b): # 添加self参数 return a + b # 正确调用 s = Solution() print(s.addTwoNumbers(3, 5)) # 输出8 ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值