力扣:兩數求和

給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,並且它們的每個節點只能存儲 一位 數字。

如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。

您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
示例:

輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807

解題代碼:

package leetcode;

public class addTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) {
            return null;
        } else if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        } else {
            int add = l1.val + l2.val;
            if (add >= 10) {
                jinwei(l1);
            }
            ListNode sum = new ListNode(add % 10);
            sum.next = addTwoNumbers(l1.next, l2.next);
            return sum;
        }
    }
    void jinwei(ListNode listNode) {
        if (listNode.next != null) {
            listNode.next.val = listNode.next.val + 1;
            if (listNode.next.val == 10) {
                listNode.next.val = 0;
                jinwei(listNode.next);
            }
        } else {
            listNode.next = new ListNode(1);
        }
    }

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章