(LeetCode) Add Two Numbers

https://leetcode.com/problems/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.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.


題目是給定兩個非空倒敘排列的鏈表,要求將兩個鏈表相加形成一個新的鏈表。新的鏈表同樣是倒敘排列。如2-4-3 + 5-6-4, 即爲342+465 = 708 , 所得鏈表需要爲8-0-7.

本題不用考慮倒序問題,因爲正着加和反着加結果是一樣的,結果所得鏈表也爲倒序。

/**
 * 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) {
            int sum = 0;
            ListNode temp = new ListNode(0);//初始化新鏈表,用於操作
            ListNode temp1 = temp;//保存新鏈表頭部,用於返回。
            while (l1 != null || l2 != null) {
                sum /= 10;//處理進位問題
                if (null != l1) {//相加
                    sum += l1.val;
                    l1 = l1.next;
                }
                if (null != l2) {
                    sum += l2.val;
                    l2 = l2.next;
                }

                temp.next = new ListNode(sum % 10);//保存相加結果的個位數
                temp = temp.next;
            }
            if(sum/10 == 1)//如果此時一個鏈表已經爲空,即兩個鏈表長度不同,則需要處理最後一位的問題。(如倒數第二位進位爲9,最後一個鏈表末尾數爲9,則9+9=18,進位1,放到最後一位)
                temp.next = new ListNode(1);
            return temp1.next;//從temp的next開始返回
    }
}
放一個相似解法,和上面區別不大
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode head = new ListNode(0);
    ListNode result = head;
    int carry = 0;
    
    while (l1 != null || l2 != null || carry > 0) {
        int resVal = (l1 != null? l1.val : 0) + (l2 != null? l2.val : 0) + carry;
        result.next = new ListNode(resVal % 10);
        carry = resVal / 10;
        l1 = (l1 == null ? l1 : l1.next);
        l2 = (l2 == null ? l2 : l2.next);
        result = result.next;
    }
    
    return head.next;
}

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