Fifth. 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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
感覺這種思維方式真的很妙。通過一個carry來得到進位數,通過一個sum來算和。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode prehead = new ListNode(-1); // 建立一個哨兵節點
ListNode head = prehead; // 建立一個指標
int carry = 0; // 儲存進位數
while(l1 != null || l2 != null){ // 只有兩個連結串列都為空的時候才會結束迴圈
int x = l1 == null ? 0 : l1.val; // 如果本連結串列已經為空了,就返回0,否則返回當前節點的值
int y = l2 == null ? 0 : l2.val;
int sum = x + y + carry; // 計算一下當前x + y的值,再加上進位值.
carry = sum / 10; // 計算一下當前的進位值
head.next = new ListNode( sum % 10 ); // 指向下一個節點為sum % 10. 如果 sum > 9,則為個位數,如果sum <= 9,則還是sum
head = head.next; // 維護指標
// if連結串列不為空才會維護指標(防止空指標異常)
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}
// 出於對最後一位的考慮,如果最後carry為1的話,說明兩個連結串列的最後一位相加>9,這個時候就需要在連結串列的後面再加一位.
if(carry == 1){
head.next = new ListNode(carry);
}
return prehead.next;
}
}
相關文章
- LeetCode2: Add two numbers(兩數相加)LeetCode
- LeetCode 2 Add Two NumbersLeetCode
- [LeetCode] Add Two Numbers 兩個數字相加LeetCode
- LeetCode-2 Add Two NumbersLeetCode
- LeetCode 2. Add Two NumbersLeetCode
- LeetCode OJ : 2 Add Two NumbersLeetCode
- Leetcode Add Two NumbersLeetCode
- [Leetcode] 2. Add Two Numbers QuestionEditorial SolutionLeetCode
- Leetcode-Add Two NumbersLeetCode
- Add Two Numbers leetcode javaLeetCodeJava
- LeetCode: Two sum(兩數之和)LeetCode
- [LeetCode] Two Sum 兩數之和LeetCode
- leetcode 兩數相加(add two numbers) Python程式設計實現LeetCodePython程式設計
- LeetCode 解題報告 - 2. Add Two NumbersLeetCode
- [leetCode][016] Add Two NumbersLeetCode
- python leetcode 之兩數之和(two sum)PythonLeetCode
- Add_Two_Numbers python 求解Python
- LeetCode 之 JavaScript 解答第一題 —— 兩數之和(Two Sum)LeetCodeJavaScript
- LeetCode:兩數之和LeetCode
- LeetCode - 兩數之和LeetCode
- LeetCode 1 兩數之和LeetCode
- leetcode #1 兩數之和LeetCode
- LeetCode之兩數之和LeetCode
- LeetCode-兩數之和LeetCode
- LeetCode 1. 兩數之和LeetCode
- LeetCode-1. 兩數之和LeetCode
- Leetcode[421] Maximum XOR of Two Numbers in an ArrayLeetCode
- 力扣.1 兩數之和 N 種解法 two-sum力扣
- leetcode-0001 兩數之和LeetCode
- 組隊刷LeetCode - 兩數之和LeetCode
- LeetCode 1 兩數之和(簡單)LeetCode
- [LeetCode 刷題] 1. 兩數之和LeetCode
- LeetCode題集-1- 兩數之和LeetCode
- 兩數之和
- [LeetCode] Divide Two Integers 兩數相除LeetCodeIDE
- LeetCode - 15. 三數之和 2LeetCode
- 每日一道 LeetCode (1):兩數之和LeetCode
- [演算法] LeetCode 1.兩數之和演算法LeetCode