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 : 

常规数学运算:右对齐,高位补0

非常规数学运算:对齐,位补0,所以本问题可以直接采用非常规数学运算计算。

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.

posted on 2018-11-16 21:50  wangzhch  阅读(174)  评论(0编辑  收藏  举报

导航