【LeetCode 002】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.

思路:依次求解即可。两个需要注意的地方:一,两个链表不等长,这时候若其中一个链表加完,则后面都是0. 这可以每一步都判断; 二,加法进位,链表加完后需要检查进位是否为0,否则需要单独再加一个结点。

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int sum=0,carry=0;
        ListNode* head=new ListNode(0),* tmp=head;
        while(l1||l2||carry){
            int sum=(l1?l1->val:0)+(l2?l2->val:0)+carry;         
            carry=sum/10;
            tmp->next=new ListNode(sum%10);
            tmp=tmp->next;
            l1=l1?l1->next:nullptr;
            l2=l2?l2->next:nullptr;
        }
        return head->next;
    }
C++中,指针可以是否为空可以直接当做bool型来判断,所以
            (l1->next!=nullptr)||(l2->next!=nullptr)||c!=0 
可以简化成:  l1||l2||c

猜你喜欢

转载自blog.csdn.net/sinat_38972110/article/details/82924657