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-2 Add Two NumbersLeetCode
- LeetCode 2. Add Two NumbersLeetCode
- leetcode 兩數相加(add two numbers) Python程式設計實現LeetCodePython程式設計
- LeetCode: Two sum(兩數之和)LeetCode
- python leetcode 之兩數之和(two sum)PythonLeetCode
- Add_Two_Numbers python 求解Python
- LeetCode 之 JavaScript 解答第一題 —— 兩數之和(Two Sum)LeetCodeJavaScript
- 1.兩數之和 Two Sum
- LeetCode - 兩數之和LeetCode
- LeetCode:兩數之和LeetCode
- leetcode #1 兩數之和LeetCode
- LeetCode 1 兩數之和LeetCode
- LeetCode之兩數之和LeetCode
- LeetCode-兩數之和LeetCode
- LeetCode-1. 兩數之和LeetCode
- leetcode-0001 兩數之和LeetCode
- LeetCode 1. 兩數之和LeetCode
- 2020/10/31·Leetcode·兩數之和LeetCode
- LeetCode 1 兩數之和(簡單)LeetCode
- 組隊刷LeetCode - 兩數之和LeetCode
- Sum of Square Numbers 平方數之和
- [LeetCode 刷題] 1. 兩數之和LeetCode
- LeetCode-Python 1. 兩數之和LeetCodePython
- 2020-10-12 Leetcode 兩數之和LeetCode
- LeetCode題集-1- 兩數之和LeetCode
- 力扣.1 兩數之和 N 種解法 two-sum力扣
- LeetCode - 15. 三數之和 2LeetCode
- LeetCode每日一題:兩數之和(No.1)LeetCode每日一題
- #leetcode刷題之路1-兩數之和LeetCode
- [演算法] LeetCode 1.兩數之和演算法LeetCode
- 每日一道 LeetCode (1):兩數之和LeetCode
- leetCode解題記錄1 - 兩數之和LeetCode
- Leetcode力扣1 兩數之和(Python版)LeetCode力扣Python
- LeetCode每日一題 (32)1. 兩數之和LeetCode每日一題
- LeetCode 2——兩數相加LeetCode
- 【LeetCode】2 兩數相加LeetCode