1. 程式人生 > 其它 >力扣2. 兩數相加

力扣2. 兩數相加

2. 兩數相加

2. 兩數相加
難度:中等
描述:給你兩個 非空 的連結串列,表示兩個非負的整數。它們每位數字都是按照 逆序 的方式儲存的,並且每個節點只能儲存 一位 數字。請你將兩個數相加,並以相同形式返回一個表示和的連結串列。你可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。

示例 1:

輸入:l1 = [2,4,3], l2 = [5,6,4]
輸出:[7,0,8]
解釋:342 + 465 = 807.

示例 2:

輸入:l1 = [0], l2 = [0]
輸出:[0]

示例 3:

輸入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
輸出:[8,9,9,9,0,0,0,1]

/**
 * 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* res=new ListNode(0);
        ListNode* cur=res;
        int carry=0;
        while(l1|| l2|| carry){     //只要有一個不為空就迴圈
        //只要l1,l2不為空都會執行
         if (l1!=NULL){
             carry+=l1->val;
         }
         if (l2!=NULL){
             carry+=l2->val;
         }
         //比如7+5=12   上2進1
         ListNode* tem=new ListNode(carry%10);
         cur->next=tem;
         cur=cur->next;
         //指向l1的指標右移
         if(l1!=NULL)
         l1=l1->next;
         if(l2!=NULL)
         l2=l2->next;
         //超過10進1
         carry=carry/10;
        }
        return res->next;
    }
};