leetcode-2-Add Two Numbers

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.
Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

解析

用LinkList代表整數(shù)中每一個(gè)數(shù)字,模擬加法進(jìn)位的方式進(jìn)行求和計(jì)算。例如:2 -> 4 -> 3
和5 -> 6 -> 4,先計(jì)算個(gè)位數(shù) 2和5的和為7, 十位數(shù) 4和6的和為10,逢十進(jìn)一,則該位的數(shù)字
為0,產(chǎn)生一位進(jìn)位1到百位參與百位的數(shù)字求和。那么百位的結(jié)果:3 + 4 + 1(這個(gè)1就是剛剛十位
相加產(chǎn)生的進(jìn)位),百位計(jì)算結(jié)果為8,所以最終返回結(jié)果 7 -> 0 -> 8

代碼(C++)

/**
 * 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* pRoot = NULL;
        
        do {
            if (l1 == NULL) {
                pRoot = l2;
                break;
            } 
            
            if (l2 == NULL) {
                pRoot = l1;
                break;
            }
            
            int sum = l1->val + l2->val;
            int digit = sum % 10;
            int carry = sum / 10;
            pRoot = new ListNode(digit);
            ListNode* pTail = pRoot;
            l1 = l1->next;
            l2 = l2->next;

            while (l1 != NULL || l2 != NULL) {
                int sum = ((l1 != NULL) ? l1->val : 0) + ((l2 != NULL) ? l2->val : 0) + carry;
                int digit = sum % 10;
                carry = sum / 10;
                
                ListNode* pNew = new ListNode(digit);
                pTail->next = pNew;
                pTail = pNew;
                
                l1 = l1 != NULL ? l1->next : NULL;
                l2 = l2 != NULL ? l2->next : NULL;
            }
            
            if (carry == 1) {
                ListNode* pNew = new ListNode(carry);
                pTail->next = pNew;
            }
        } while (false);
        
        return pRoot;
    }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容