2. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

eg:

   2 4 3
 + 5 6 4
 = 7 0 8

   9 9 9
 + 8 1
 = 7 1 0 1

維護(hù)dummy, curt Node, while循環(huán)來(lái)計(jì)算從高到低數(shù)位上的加法,每加完一次l1 = l1.next, l2 = l2.next. 要注意用一個(gè)carry來(lái)記錄是否進(jìn)位,如果carry == 0 則不需要,若carry > 0(只能為1)時(shí),要讓該位的運(yùn)算加上carry. 還要記得處理最后一味存在進(jìn)位的情況,比如

  5 
+ 5
= 0 1

像這樣的話,l1, l2已經(jīng)是null了,那么就要專門來(lái)說(shuō)carry > 0的情況下還得在形成的LinkedList尾巴后面跟上一個(gè)val = 1的Node.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null){
            return null;
        }    
        if (l1 == null){
            return l2;
        }
        if (l2 == null){
            return l1;
        }
        ListNode dummy = new ListNode(-1);
        ListNode curt = dummy;
        int carry = 0;
        while (l1 != null && l2 != null){
            int sum = l1.val + l2.val + carry;
            int digit = sum % 10;
            carry = sum / 10;
            ListNode node = new ListNode(digit);
            curt.next = node;
            curt = curt.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        
        while (l1 != null){
            int sum = l1.val + carry;
            int digit = sum % 10;
            carry = sum / 10;
            ListNode node = new ListNode(digit);
            curt.next = node;
            curt = curt.next;
            l1 = l1.next;
        }
        while (l2 != null){
            int sum = l2.val + carry;
            int digit = sum % 10;
            carry = sum / 10;ss
            ListNode node = new ListNode(digit);
            curt.next = node;
            curt = curt.next;
            l2 = l2.next;
        }
        if (carry > 0){
            ListNode node = new ListNode(1);
            curt.next = node;
        }
        return dummy.next;    
    }  
}
最后編輯于
?著作權(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)容

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