LeetCodeHOT100——第二题:两数相加(No.2)

LeetCode HOT100——第二题:两数相加(No.2)

思路

l1.val、l2.val、carry(进位)之和确定 l3。
注意事项: 注意链表的建立方法,确认链表尾部是否为空。

代码

python

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        l3 = head = ListNode()
        carry = 0
        while l1 or l2 or carry:
            sum = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry
            (sum, carry) = (sum, 0) if sum < 10 else (sum - 10, 1)
            l3.next = ListNode(sum)
            l3 = l3.next 
            l1 = l1.next if l1 else None 
            l2 = l2.next if l2 else None
        return head.next

C++

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* l3 = new(ListNode);
        ListNode* head = l3;
        int carry = 0;
        while(l1 || l2 || carry)
        {
            int sum = 0;
            if(l1) sum += l1->val;
            if(l2) sum += l2->val;
            sum += carry;
            if(sum >= 10)
            {
                sum -= 10;
                carry = 1;
            }
            else carry = 0;
            l3->next = new ListNode(sum);
            l3 = l3->next;
            if(l1) l1 = l1->next; else nullptr;
            if(l2) l2 = l2->next; else nullptr;
        }
        return head->next;
    }
};

其他

在写C++代码时遇到了bug:runtime error: member access within address 0x602000000000 with insufficient space for an object of,百度检查后发现是建立指针后没有初始化,原代码如下:

ListNode* l3;

参考链接

上一篇:字符串乘法,简单易懂,包含由字符串加法和字符串与单字符乘法结合而成


下一篇:五个砝码