Add Two Numbers[LeetCode 2]

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cyrususie/article/details/78841251

Answer


class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int temp1 = 0, temp2 = 0;
        ListNode* t1 = l1;
        ListNode* t2 = l2;
        ListNode* ans = new ListNode(0);
        ListNode* curr = ans;
        int carry = 0;
        while(t1 != NULL | t2 != NULL) {
            temp1 = (t1 != NULL)? t1 -> val: 0;
            temp2 = (t2 != NULL)? t2 -> val : 0;
            int sum = carry + temp1 + temp2;
            //cout << temp1 << " " << temp2 << " " << sum << endl;
            curr -> next = new ListNode(sum % 10);
            curr = curr -> next;
            t1 = (t1!= NULL)? t1 -> next : NULL;
            t2 = (t2!= NULL)? t2 -> next : NULL;
            carry = sum / 10;
        }
        if (carry > 0) {
            curr -> next = new ListNode(carry);
        }
        return ans -> next;
    }
};

猜你喜欢

转载自blog.csdn.net/cyrususie/article/details/78841251