Leek 2. Adding two numbers

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 neither number starts with a zero other than the number zero.

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
 Output: [7,0,8]
 Explanation: 342 + 465 = 807.

Example 2:

Input: l1 = [0], l2 = [0]
 Output: [0]

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
 Output: [8,9,9,9,0,0,0,1]

hint:

  • The number of nodes in each linked list is in the  [1, 100] range
  • 0 <= Node.val <= 9
  • The title data guarantees that the number represented by the list does not contain leading zeros

 

/**
 * 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 *p1 = nullptr;
        ListNode *p2 = nullptr;
        int jinwei = 0;
        int sum = 0;
        while(l1||l2){
            int n1 = l1?l1->val:0;
            int n2 = l2?l2->val:0;
            sum = n1 + n2 + jinwei;
            if(!p1){
                p1 = p2 = new ListNode( sum % 10);
            }else{
                p2->next = new ListNode(sum % 10);
                p2 = p2->next;
            }
            jinwei = sum /10;
            if(l1)
                l1 = l1->next;
            if(l2)
                l2 = l2->next;
            
        }
        if (jinwei > 0) {
            p2->next = new ListNode(jinwei);
        }
        return p1;
    }
};

おすすめ

転載: blog.csdn.net/Recursions/article/details/128506484