美文网首页
Add Two Numbers in the List

Add Two Numbers in the List

作者: QuentinnYANG | 来源:发表于2018-10-30 14:53 被阅读0次

    Problem declaration

    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.

    /*
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    

    C++ Solution

    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.

    //Solution.h
    #ifndef CLIONPROJECTS_SOLUTION_H
    #define CLIONPROJECTS_SOLUTION_H
    
    class Solution {
    public:
        struct ListNode {
            int val;
            ListNode *next;
            ListNode(int x) : val(x), next(nullptr) {}
        };
    
        static ListNode* addTwoNumbers(ListNode* l1, ListNode* l2);
    };
    #endif //CLIONPROJECTS_SOLUTION_H
    
    //Solution.cpp
    #include "Solution.h"
    
    Solution::ListNode* Solution::addTwoNumbers(ListNode* l1, ListNode* l2)
    {
        auto *dummyHead = new ListNode(0);
        auto *currentNode = dummyHead;
        int carry = 0;
        while(nullptr != l1 || nullptr != l2)
        {
            int a = (nullptr != l1) ? l1->val : 0;
            int b = (nullptr != l2) ? l2->val : 0;
            int sum = a + b + carry;
            carry = sum / 10;
            currentNode->next = new ListNode(sum % 10);
            currentNode = currentNode->next;
    
            //Point to next node
            if(nullptr != l1) l1 = l1->next;
            if(nullptr != l2) l2 = l2->next;
        }
        //Process carry in the end
        if(carry > 0)
        {
            currentNode->next = new ListNode(carry);
        }
        return dummyHead->next;
    }
    
    //main.cpp
    #include <iostream>
    #include "Solution.h"
    
    int main(int argc, char* argv[])
    {
        Solution::ListNode x[3] = {2, 4, 3}, y[3] = {5, 6, 4};
    
        x[0].next = &x[1];
        x[1].next = &x[2];
        x[2].next = nullptr;
    
        y[0].next = &y[1];
        y[1].next = &y[2];
        y[2].next = nullptr;
    
        Solution::ListNode* z = Solution::addTwoNumbers(x, y);
        std::cout << z->val << z->next->val << z->next->next->val << std::endl;
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:Add Two Numbers in the List

          本文链接:https://www.haomeiwen.com/subject/wtfgtqtx.html