Add Two Numbers

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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

#include <iostream>

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) {
        auto dummy = new ListNode(-1), cur = dummy;
        int t = 0;  // 进位值
        while(l1 || l2 || t){
            if(l1) {
                t += l1->val;
                l1 = l1->next;
            }
            if(l2){
                t += l2->val;
                l2 = l2->next;
            }
            cur->next = new ListNode(t % 10); // 只要个位
            cur = cur->next;
            t /= 10;    // int 值 除法 还是 int 值
        }
        return dummy->next;
    }
};

int main() {
    auto dummy1 = new ListNode(-1);
    auto dummy2 = new ListNode(-1);
    dummy1->next = new ListNode(2);
    dummy1->next->next = new ListNode(4);
    dummy1->next->next->next = new ListNode(3);
    dummy2->next = new ListNode(5);
    dummy2->next->next = new ListNode(6);
    dummy2->next->next->next = new ListNode(4);
    Solution solution;
    auto result = solution.addTwoNumbers(dummy1->next, dummy2->next);
    while(result){
        std::cout << result->val << ", ";
        result = result->next;
    }
    return 0;
}

Leave a Comment

Your email address will not be published. Required fields are marked *

PHP 8.1.1 - 21.022 ms, 0 Q