LeetCode_2_两数相加
生活随笔
收集整理的這篇文章主要介紹了
LeetCode_2_两数相加
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.?
鏈表類:
class ListNode{int val;ListNode next;public ListNode(int val) {this.val = val;} }?
實現類:
public static ListNode addTwoNumbers(ListNode l1 , ListNode l2){ListNode l = null;int temp = 0;l = new ListNode(l1.val+l2.val);ListNode q = new ListNode(0);//q指向第一個結點q = l;while(l1.next!=null && l2.next!=null){if(l.val<10){l.next =new ListNode(l1.next.val+l2.next.val);}else{temp = l.val;l.val = temp%10;l.next = new ListNode(temp/10+l1.next.val+l2.next.val);}l = l.next;l1 = l1.next;l2 = l2.next;}while (l1.next != null && l2.next == null) {if (l.val>=10) {temp = l.val;l.val = temp%10;l.next = new ListNode(temp/10+l1.next.val);}else {l.next = new ListNode(l1.next.val);}l = l.next;l1 = l1.next;}while (l1.next == null && l2.next != null) {if (l.val>=10) {temp = l.val;l.val = temp%10;l.next = new ListNode(temp/10+l2.next.val);}else {l.next = new ListNode(l2.next.val);}l = l.next;l2 = l2.next;}//處理最后一個數,是否需要進位if (l.val>=10) {temp = l.val;l.val = temp%10;l.next = new ListNode(temp/10);}l = q;return l;}?
注意點:
1,定義指針q指向第一個結點。獲得所求的結果后,將鏈表l指向q,即鏈表的第一個節點。
2,鏈表l1,l2相加時,需考慮進位問題。
?
轉載于:https://www.cnblogs.com/wkcode/p/8663922.html
總結
以上是生活随笔為你收集整理的LeetCode_2_两数相加的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 任意两点间的最短路问题(Floyd-Wa
- 下一篇: 【洛谷P1378】油滴扩展