美文网首页
2. Add Two Numbers

2. Add Two Numbers

作者: _SANTU_ | 来源:发表于2017-01-04 22:06 被阅读0次

    You are given two linked lists representing two non-negative numbers. 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.

    **Input: ** (2 -> 4 -> 3) + (5 -> 6 -> 4)
    **Output: ** 7 -> 0 -> 8

    C++ version:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            int carry = 0;
            int sumOfOne = l1->val + l2->val + carry;
            carry = sumOfOne/10;
            sumOfOne %= 10;
            struct ListNode *result = new struct ListNode(sumOfOne);
            struct ListNode *cur = result;
            l1 = l1->next;
            l2 = l2->next;
            
            while(l1 || l2){
                if(l1&&l2){
                    sumOfOne = l1->val + l2->val + carry;
                    l1 = l1->next;
                    l2 = l2->next;
                }else if(l1==NULL){
                    sumOfOne = l2->val + carry;
                    l2 = l2->next;
                }else if(l2==NULL){
                    sumOfOne = l1->val + carry;
                    l1 = l1->next;
                }
                carry = sumOfOne/10;
                sumOfOne %= 10;
                // printf("sumOfOne: %d\n",sumOfOne);
                struct ListNode *oneNode = new struct ListNode(sumOfOne);
                cur->next = oneNode;
                cur = cur->next;
                // printf("cur->val: %d\n",cur->val);
            }
            if(carry==1){
                struct ListNode *oneNode = new struct ListNode(carry);
                cur->next = oneNode;
                cur = cur->next;
            }
            return result;
        }
    };
    

    相关文章

      网友评论

          本文标题:2. Add Two Numbers

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