Leecode Week2: Add Two Numbers

Week2:Add Two Numbers(Medium)

1. Question

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

2. Solution

/**
 * 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) {
        ListNode *temp = new ListNode(0);
        ListNode *p = temp;
        int carry = 0;
        int flag = false;
        while(l1 || l2 || carry) {
            if(flag) {
                p->next = new ListNode(0);
                p = p->next;
            }
            int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
            carry = sum / 10;
            p->val = sum % 10;
            l1 = l1 ? l1->next : l1;
            l2 = l2 ? l2->next : l2;
            flag = true;
        }
        return temp;
    }
};

思路:利用l1、l2和carry来判断是否还需要对p->next进行赋值,其中carry为l1和l2当前位的进位,同时利用flag来避免最后多出一位。时间复杂度为O(n)。

你可能感兴趣的:(Leecode)