Leet Code OJ 2. Add Two Numbers [Difficulty: Medium]
題目:
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
翻譯:
給你2個鏈表,代表2個非負整數。鏈表中整數的每一位數字的存儲是反序的,數組的每個節點都包含一個數字。把2個非負整數相加,并且用一個鏈表返回。
輸入: (2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出: 7 -> 0 -> 8
分析:
由于剛好鏈表中數的存儲是反序,也就是個位在最前面,正好方便我們從低位開始加。需要注意的幾個點:
1. 傳入[][],也就是2個空鏈表,要返回null
2. 傳入[0][0],也就是2個整數是0的處理,要返回[0]
3. 傳入[5][5],要新增一個節點,存儲進位。也就是判斷是否結束,要根據2個鏈表是否為空和是否有進位來判斷。
Java版代碼:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/ public class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {if(l1==null&&l2==null){return null;}ListNode head=new ListNode(0);ListNode currentNode=head;int fix=0;while(l1!=null||l2!=null||fix!=0){int val1=0;int val2=0;if(l1!=null){val1=l1.val;l1=l1.next;}if(l2!=null){val2=l2.val;l2=l2.next;}int sum=val1+val2+fix;fix=0;if(sum>9){fix=1;sum-=10;}currentNode.next=new ListNode(0);currentNode.next.val=sum;currentNode=currentNode.next;}if(head.next==null){head.next=new ListNode(0);}return head.next;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 2. Add Two Numbers [Difficulty: Medium]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 119. Pa
- 下一篇: LeetCode刷题指南(一)