LeetCode Algorithm 0002 - Add Two Numbers (Medium)

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/darkrabbit/article/details/82723282

LeetCode Algorithm 0002 - Add Two Numbers (Medium)

Problem Link: https://leetcode.com/problems/add-two-numbers/description/


Description

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.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/add-two-numbers/description/

namespace P2AddTwoNumbers
{
    struct ListNode
    {
        int val;
        ListNode *next;
        ListNode(int x) : val(x), next(NULL)
        {
        }
    };

    class Solution
    {
        public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
        {
            ListNode* head = new ListNode(0);
            ListNode* current = head;
            int qVal = 0;
            int sumVal = 0;
            ListNode* next = NULL;
            ListNode* tmp1 = l1;
            ListNode* tmp2 = l2;

            while (tmp1 != NULL || tmp2 != NULL)
            {
                sumVal = qVal;

                if (tmp1 != NULL)
                {
                    sumVal += tmp1->val;
                    tmp1 = tmp1->next;
                }

                if (tmp2 != NULL)
                {
                    sumVal += tmp2->val;
                    tmp2 = tmp2->next;
                }

                qVal = sumVal / 10;
                current->val = sumVal % 10;

                if (tmp1 != NULL || tmp2 != NULL)
                {
                    next = new ListNode(0);
                    current->next = next;
                    current = current->next;
                }
            }

            if (qVal > 0)
            {
                next = new ListNode(qVal);
                current->next = next;
            }

            return head;
        }
    };
}

猜你喜欢

转载自blog.csdn.net/darkrabbit/article/details/82723282