LeetCode刷题笔记--2. Add Two Numbers

2. Add Two Numbers

Medium

46781177FavoriteShare

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse orderand 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.

AC代码如下:

/**
 * 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) {
        return addByBit(l1,l2,0);
    }
    
    ListNode* addByBit(ListNode* l1, ListNode* l2,int carry)
    {
        if(l1==NULL)l1=new ListNode(0);//如果l1为空,l1增加一个新节点为0
        if(l2==NULL)l2=new ListNode(0);//如果l2为空,l2增加一个新节点为0
        ListNode *l=new ListNode((l1->val+l2->val+carry)%10);//计算加的和
        carry=(l1->val + l2->val + carry) / 10;//计算进位
        if(l1->next!=NULL||l2->next!=NULL||carry==1)//注意此处的条件,如果l1还有值,或者l2还有值,或者进位有值
        {
            l->next=addByBit(l1->next,l2->next,carry);//递归
        }
        return l;//最后返回I
    }
    
};

你可能感兴趣的:(LeetCode刷题笔记--2. Add Two Numbers)