鏈接:https://leetcode.com/problems/add-two-numbers/
原題:
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
分析:
這道題實際上就是倒敘的鏈表颁虐,最終算出和侥袜,并以鏈接的形式呈現(xiàn)。
還是循環(huán)包吝,但要注意可能有進(jìn)1位 以及 兩個數(shù)字長度不同的問題
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode l1tmp = l1;
ListNode l2tmp = l2;
int add1 = 0;
while (true) {
int l1num = l1tmp.val;
int l2num = l2tmp ==null?0:l2tmp.val;
int value = l1num + l2num + add1;
add1 = value / 10;
value = value % 10;
l1tmp.val = value;
if (l1tmp.next == null) {
if((l2tmp!=null && l2tmp.next!=null)|| add1!=0) {
l1tmp.next = new ListNode(0);
} else {
break;
}
}
l1tmp = l1tmp.next;
l2tmp = l2tmp == null?null:l2tmp.next;
}
return l1;
}
代碼效率沒有很高锥余,待優(yōu)化