Intuitive c++ code


  • 12
    K
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* head = new ListNode(0);
            ListNode* cur = head;
            int plus = 0;
            while (l1 || l2) {
                int num = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + plus;
                if (num >= 10) {
                    num -= 10;
                    plus = 1;
                } else plus = 0;
                cur->next = new ListNode(num);
                cur = cur->next;
                if (l1) l1 = l1->next;
                if (l2) l2 = l2->next;
            }
            if (plus) cur->next = new ListNode(1);
            return head->next;
        }
    };

  • 1
    A

    Thanks. Modified a bit to eliminate some conditions.

    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* head = new ListNode(0);
            ListNode* cur = head;
            int carry = 0;
            while (l1 || l2 || carry) {
                int num = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
                carry = num / 10;
                cur->next = new ListNode(num % 10);
                cur = cur->next;
                if (l1) l1 = l1->next;
                if (l2) l2 = l2->next;
            }
            return head->next;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.