LeetCode Interview Qustions: Add Two Number

直接使用加法

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ListNode* result = new ListNode(0);
        ListNode* p = result;
        int carray_bit = 0;
        while(l1 && l2) {
            p->next = new ListNode(0);
            p = p->next;
            
            p->val = l1->val + l2->val + carray_bit;
            if (p->val >= 10) {
                p->val = p->val%10;
                carray_bit = 1;
            } else {
                carray_bit = 0;
            }
            l1 = l1->next;
            l2 = l2->next;
        }
        
        while(l1) {
            p->next = new ListNode(0);
            p = p->next;
            
            p->val = l1->val + carray_bit;
            if (p->val >= 10) {
                p->val = p->val%10;
                carray_bit = 1;
            } else {
                carray_bit = 0;
            }
            l1 = l1->next;
        }
        
        while(l2) {
            p->next = new ListNode(0);
            p = p->next;
            
            p->val = l2->val + carray_bit;
            if (p->val >= 10) {
                p->val = p->val%10;
                carray_bit = 1;
            } else {
                carray_bit = 0;
            }
            l2 = l2->next;
        }
        
        if (carray_bit) {
            p->next = new ListNode(1);
            p = p->next;            
        }
        return result->next;        
    }
};


你可能感兴趣的:(interview)