zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Leetcode 题目002-用链表实现大数加法

LeetCode链表 实现 题目 加法 大数 002
2023-06-13 09:13:08 时间

解答:

c++ 版:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* root = new ListNode;
        ListNode* cursor = root;
        int carry = 0; //进位为1,否则为0
        while(l1 || l2 || carry) {
            int l1Val = l1 ? l1->val : 0;
            int l2Val = l2 ? l2->val : 0;
            int sumVal = l1Val + l2Val + carry;
            carry = sumVal / 10; //提取十位数,0或者1
            
            ListNode *sumNode = new ListNode(sumVal % 10);
            cursor->next = sumNode;
            cursor = sumNode;
            
            if(l1) l1 = l1->next;
            if(l2) l2 = l2->next;
        }
        
        return root->next;
    }
};

Python 版:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def addTwoNumbers(self, l1, l2):
        root = ListNode()
        cursor =root
        carry = 0
        while(l1 is not None or l2 is not None or carry!=0): # l1 这里等价于 l1 is not None
            l1val = l1.val if l1 else 0
            l2val = l2.val if l2 else 0
            sumval = l1val + l2val + carry
            carry = 1 if sumval > 9 else 0
            
            sumNode = ListNode(sumval%10)
            cursor.next = sumNode
            cursor = sumNode
            
            if l1 is not None: l1 = l1.next
            if l2 is not None: l2 = l2.next
        return root.next