LeetCode - 2. 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 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.

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

代碼

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    //我的方法,勝過80%人
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if(l1 == NULL) return l2;
        if(l2 == NULL) return l1;
        ListNode *head = l1,*rear;
        int flag = 0;   //進位
        int sum;
        while(l1 || l2)
        {
            if(l1 && l2 )
            {
                sum = l1->val + l2->val + flag;
                l1->val = sum % 10;
                flag = sum / 10;
                rear = l1;
                l1 = l1->next;
                l2 = l2->next;
            }
            else if(l1 && l2 == NULL)
            {
                sum = l1->val + flag;
                l1->val = sum % 10;
                flag = sum / 10;
                rear = l1;
                l1 = l1->next;
            }
            else if(l1 == NULL && l2)
            {
                sum = l2->val + flag;
                l2->val = sum % 10;
                flag = sum / 10;
                rear = rear->next = l2;
                l2 = l2->next;
            }
        }
        if(flag)  //加到最後,如果有進位,則新建一個節點
            rear->next = new ListNode(1);
        return head;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章