LeetCode 2. Add Two Numbers

2. Add Two Numbers

Difficulty: medium 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.

乍一眼一看, woq, 这不是喜闻乐见的大数吗…

only version:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if (l1->next == NULL && l2->next == NULL &&
            l1->val == 0 && l2->val == 0) {
            return new ListNode(0);
        }
        bool l1s, l2s;
        int addOne = 0;
        
        ListNode *res = NULL, *itr;
        
        while (l1 != NULL || l2 != NULL) {
            int bit = (l1 != NULL ? l1->val : 0) + (l2 != NULL ? l2->val : 0) + addOne;
            addOne = 0;
            if (bit > 9) {
                bit -= 10;
                addOne = 1;
            }
            
            if (res == NULL) {
                res = new ListNode(bit);
                itr = res;
            } else {
                itr->next = new ListNode(bit);
                itr = itr->next;
            }
            
            if (l1 != NULL)
                l1 = l1->next;
            if (l2 != NULL)
                l2 = l2->next;
        }
        
        if (addOne != 0) {
            itr->next = new ListNode(addOne);
        }
        
        return res;
    }
};

Rate:
Runtime: 24 ms, faster than 69.24% of C++ online submissions for Add Two Numbers.
Memory Usage: 10.3 MB, less than 70.28% of C++ online submissions for Add Two Numbers.

这套冗长的大数加法逻辑, 最初就是由我自己经过很多次测试固定下来的, 个人认为这个算法的好处, 第一, 我自己一直都在用, 所以比较熟悉, 并且也没有想过要优化的; 第二, 适用于所有进制的加法.
时间和内存使用算是比较理想的, 但是肯定是比不过讨论区的大佬.

不过这次的体验比较糟糕, 讨论区并没有看到什么好的代码, 除了比我的简洁的, 但是我觉得没有必要.