[leetcode練習記錄]兩數相加

題目描述:

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

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

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

示例:

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

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/add-two-numbers
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

 

個人解答:

/**
 * 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 head = new ListNode(0);
		ListNode node = head;
		int sum = 0;
		
		while(true) {
			node.next = new ListNode((l1.val + l2.val + sum) % 10);
			node = node.next;
			sum = (l1.val + l2.val + sum) /10 ;
			if (l1.next == null) {
				l1.val = 0;
				if (l2.next == null) {
					if(sum != 0) {
						node.next = new ListNode(sum);
					}
					break;
				}
				l2 = l2.next;
			} else {
				l1 = l1.next;
				if (l2.next == null) {
					l2.val = 0;
				} else {
					l2 = l2.next;
				}
			}
		}
		
		return head.next;
    }
}

 

官方題解:

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) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;
}

作者:LeetCode
鏈接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-xiang-jia-by-leetcode/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

 

總結:

個人在最開始做的時候考慮先用int或者long去存儲計算的彙總值,但是沒有考慮這兩種類型的精度限制,實屬慚愧。

同時在解題過程中又好幾次因爲循環的時候忘記next,導致出現死循環而超時,這些小細節後續都需要注意。

總體解題思路和官方相差不大,主要是以上細節後續需要多注意。

1. 精度

2. 死循環

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