xinyu04

导航

[Oracle] 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 contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Solution

直接模拟进位即可。

点击查看代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* newnode = new ListNode(0), *ans = newnode;
        int adv = 0;
        while(l1||l2||adv){
            int val = adv;
            if(l1)val+=l1->val;
            if(l2)val+=l2->val;
            newnode->next = new ListNode(val%10);
            newnode = newnode->next;
            if(val>9)adv=1;
            else adv=0;
            if(l1)l1=l1->next;
            if(l2)l2=l2->next;
        }
        return ans->next;
    }
};

posted on 2022-10-03 03:41  Blackzxy  阅读(20)  评论(0编辑  收藏  举报