2.兩數相加

2.兩數相加

題目描述

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

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

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

示例:

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

題解

定義一個進位位carry,一個記錄和sum,sum/10記爲進位位,sum%10爲新鏈表節點值,注意計算結束若還有進位,需要單獨添加,代碼如下

/**
 * 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) {
    ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    //定義進位位
    int carry = 0;
    //循環知道兩個鏈表均結束
    while (p != null || q != null) {
    //不空則拿節點值,空則爲0
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        //計算進位位
        carry = sum / 10;
        //新節點,值爲sum%10
        curr.next = new ListNode(sum % 10);
        //後移
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    //完成後若進位位不爲0,表示還有一位進位,不能忘記添加
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;
    }
}
提交結果

在這裏插入圖片描述

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