2. Add Two Numbers

Description

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.
輸入為兩個(gè)非空鏈表代表兩個(gè)非負(fù)的整數(shù)。這些整數(shù)以逆序的形式存儲(chǔ),并且每個(gè)元素包含一個(gè)一位數(shù)。將這兩個(gè)整數(shù)相加得到一個(gè)新的鏈表并返回。
可以假定兩個(gè)整數(shù)沒有前導(dǎo)0,除了整數(shù)0本身。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

samples

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

用鏈表運(yùn)算來表示加法,即342+465=807

Solutions

<ol>
<li> O(n)

// com.cnsumi.leetcode.algorithms. A0002_Add_Two_Numbers.java;
class ListNode {
    int val;
    ListNode next;
    public ListNode(int val) {
        this.val = val;
    }
    
    @Override
    public String toString() {
        StringBuilder ret = new StringBuilder();
        ret.append("(");
        ListNode node = this;
        do {
            if (node != this) {
                ret.append("->");   
            }
            ret.append(node.val);
            node = node.next;
        } while (node != null);
        ret.append(")");
        return ret.toString();
    }
}

public class A0002_Add_Two_Numbers {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);
        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);
        System.out.println(l1);
        System.out.println(l2);
        System.out.println(solution1(l1, l2));
    }
    
    public static ListNode solution1(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode head = new ListNode(0);
        ListNode pre = head;
        while (l1 != null || l2 != null || carry > 0) {
            int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
            carry = sum / 10;
            pre.next = new ListNode(sum % 10);
            pre = pre.next;
            l1 = l1 == null ? l1 : l1.next;
            l2 = l2 == null ? l2 : l2.next;
        }
        return head.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)容