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) {? ? ? ? ? ?
? ? ? ? // 進位
? ? ? ? int carry = 0;
? ? ? ? // 結果骇扇,當前位
? ? ? ? ListNode res, cur;
? ? ? ? res = cur = new ListNode(0);
? ? ? ? // 兩個數(shù)的當前位
? ? ? ? ListNode n1 = l1, n2 = l2;
? ? ? ? while (n1 != null || n2 != null || carry != 0) {
? ? ? ? ? ? // 當前位數(shù)相加良狈,并加上進位
? ? ? ? ? ? cur.val = (n1 != null ? n1.val : 0) + (n2 != null ? n2.val : 0) + carry;
? ? ? ? ? ? // 清除進位
? ? ? ? ? ? carry = 0;
? ? ? ? ? ? // 如果當前產(chǎn)生了進位帝雇,則位數(shù)取個位游盲,然后設置進位
? ? ? ? ? ? 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;
? ? }
}