LeetCode 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.

题目链接:https://leetcode.com/problems/add-two-numbers/description/

题目分析:按顺序加即可,carry表示进位

/**
 * 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* helper = new ListNode(0);
        ListNode* ans = helper;
        int carry = 0;
        while (l1 != NULL || l2 != NULL || carry) {
            int num1 = l1 == NULL ? 0 : l1 -> val;
            int num2 = l2 == NULL ? 0 : l2 -> val;
            int num = num1 + num2 + carry;
            carry = num > 9 ? 1 : 0;
            ans -> next = new ListNode(num % 10);
            ans = ans -> next;
            l1 = l1 == NULL ? NULL : l1 -> next;
            l2 = l2 == NULL ? NULL : l2 -> next;
        }
        return helper -> next;
    }
};


猜你喜欢

转载自blog.csdn.net/Tc_To_Top/article/details/79073980