1. 程式人生 > >LeetCode---Add Two Numbers

LeetCode---Add Two Numbers

Question: Add Two Numbers

Detail: 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 Code:

class Solution {
    /**
     * 需要注意一下幾點:
     * 連結串列長度不相等
     * 進位情況,尤其是進位出現在最後一位
     */
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode
* pSumHead = NULL; ListNode* pSum = NULL; ListNode* p1 = l1; ListNode* p2 = l2; bool IsHead = true; int carry = 0, sum = 0, num = 0; // 處理公共長度部分 while(p1 != NULL && p2 != NULL){ sum = carry + p1->val + p2->val; carry
= (sum >= 10)? 1:0; num = sum - 10 * carry; ListNode* node = new ListNode(num); if(IsHead){// 該節點為head節點 pSum = node; pSumHead = pSum; IsHead = false; } else{ pSum->next = node; pSum = pSum->next; } p1 = p1->next; p2 = p2->next; } // 兩個連結串列長度相等,且末尾含有進位的情況 if(p1 == NULL && p2 == NULL && carry == 1) pSum->next = new ListNode(carry); // 兩個連結串列長度不相等的情況,L2的長度大於L1 if(p1 == NULL && p2 != NULL){ while(p2 != NULL){ sum = carry + p2->val; carry = (sum >= 10)? 1:0; num = sum - 10 * carry; pSum->next = new ListNode(num); pSum = pSum->next; p2 = p2->next; } if(carry == 1) pSum->next = new ListNode(carry); } // 兩個連結串列長度不相等的情況,L2的長度小於L1 if(p1 != NULL && p2 == NULL){ while(p1 != NULL){ sum = carry + p1->val; carry = (sum >= 10)? 1:0; num = sum - 10 * carry; pSum->next = new ListNode(num); pSum = pSum->next; p1 = p1->next; } if(carry == 1) pSum->next = new ListNode(carry); } return pSumHead; } };

Reports:

Runtime: 28 ms, faster than 98.14% of C++ online submissions for Add Two Numbers.