【LeetCode】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


翻譯:給定兩個非空的鏈表,表示兩個非負(fù)整數(shù)。 數(shù)字以相反的順序存儲,每個節(jié)點(diǎn)包含一個數(shù)字。 添加兩個數(shù)字并將其作為鏈表返回。

您可以假設(shè)兩個數(shù)字不包含任何前導(dǎo)零,除了數(shù)字0本身。


過程:

總結(jié):

1 . 鏈表的add
2 . 兩個鏈表長度不同,空指針
3 . 進(jìn)位問題

代碼實(shí)現(xiàn)

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (null == l1) {
            return l2;
        }
        if (null == l2) {
            return l1;
        }
        ListNode result = new ListNode(0);
        int carry = 0;  //進(jìn)位
        int sum = 0;
        while (l1 != null || l2 != null) {
            sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;  //求和
            carry = sum / 10;  //進(jìn)位
            sum = sum % 10;    //值
            ListNode root = new ListNode(sum);  //初始化一個節(jié)點(diǎn)

            result = addListNode(result, root);

            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        if (carry != 0) {
            ListNode root = new ListNode(1);  //初始化一個節(jié)點(diǎn)
            result = addListNode(result, root);
        }
        return result.next;
    }

    /**
     * add  節(jié)點(diǎn)
     *
     * @param result
     * @param root
     * @return
     */
    public ListNode addListNode(ListNode result, ListNode root) {
        if (result.next == null) {
            result.next = root;
            return result;
        }
        ListNode tmp = result.next;
        while (tmp.next != null) {
            tmp = tmp.next;
        }
        tmp.next = root;
        return result;
    }
}

ListNode類

public class ListNode {
    int val;
    ListNode next;

    public ListNode(int x) {
        val = x;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容