2020-11-22 2. Add Two Numbers

Medium

97862459Add to ListShare

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.


Example 1:

Input:l1 = [2,4,3], l2 = [5,6,4]Output:[7,0,8]Explanation:342 + 465 = 807.

Example 2:

Input:l1 = [0], l2 = [0]Output:[0]

Example 3:

Input:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]Output:[8,9,9,9,0,0,0,1]


Constraints:

The number of nodes in each linked list is in the range?[1, 100].

0 <= Node.val <= 9

It is guaranteed that the list represents a number that does not have leading zeros.


/**

* Definition for singly-linked list.

* public class ListNode {

*? ? int val;

*? ? ListNode next;

*? ? ListNode() {}

*? ? ListNode(int val) { this.val = val; }

*? ? ListNode(int val, ListNode next) { this.val = val; this.next = next; }

* }

*/

class Solution {

? ? public ListNode addTwoNumbers(ListNode l1, ListNode l2) {? ? ? ? ? ?

? ? ? ? // 進(jìn)位

? ? ? ? int carry = 0;

? ? ? ? // 結(jié)果,當(dāng)前位

? ? ? ? ListNode res, cur;

? ? ? ? res = cur = new ListNode(0);

? ? ? ? // 兩個(gè)數(shù)的當(dāng)前位

? ? ? ? ListNode n1 = l1, n2 = l2;


? ? ? ? while (n1 != null || n2 != null || carry != 0) {

? ? ? ? ? ? // 當(dāng)前位數(shù)相加,并加上進(jìn)位

? ? ? ? ? ? cur.val = (n1 != null ? n1.val : 0) + (n2 != null ? n2.val : 0) + carry;

? ? ? ? ? ? // 清除進(jìn)位

? ? ? ? ? ? carry = 0;

? ? ? ? ? ? // 如果當(dāng)前產(chǎn)生了進(jìn)位,則位數(shù)取個(gè)位,然后設(shè)置進(jìn)位

? ? ? ? ? ? if (cur.val >= 10) { cur.val -= 10; carry = 1; }


? ? ? ? ? ? // 處理下一位

? ? ? ? ? ? if (n1 != null) n1 = n1.next;

? ? ? ? ? ? if (n2 != null) n2 = n2.next;

? ? ? ? ? ? if (n1 != null || n2 != null || carry != 0) cur = cur.next = new ListNode(0);

? ? ? ? }


? ? ? ? return res;

? ? }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Type:medium You are given twonon-emptylinked lists repres...
    萌小熙喵閱讀 235評(píng)論 0 1
  • 技術(shù)交流QQ群:1027579432,歡迎你的加入! 歡迎關(guān)注我的微信公眾號(hào):CurryCoder的程序人生 1....
    CurryCoder閱讀 2,017評(píng)論 0 2
  • 這題是考察鏈表結(jié)構(gòu), 所以用recursion做, 但是也可以用兩根指針來(lái)回變換, 我因?yàn)榭吹筋}目就想到recur...
    yanyuchen閱讀 229評(píng)論 0 0
  • 設(shè)原始數(shù)據(jù)規(guī)模為n,需要采樣的數(shù)量為k 先選取數(shù)據(jù)流中的前k個(gè)元素,保存在集合A中; 從第j(k + 1 <= j...
    Impossible安徒生閱讀 338評(píng)論 0 0
  • 用 TDD 來(lái)練習(xí)完成 LeetCode 的第 2 題,題目描述如下。 LeetCode 第 2 題 題目解釋:給...
    就是91閱讀 506評(píng)論 0 2

友情鏈接更多精彩內(nèi)容