加法進位模擬運算蹄梢。需要注意corner case嫉父。
兩list位數(shù)不對齊论熙,末尾進位等等福青。
用到的java需要注意點:
- 輸入?yún)?shù)是引用,要先復(fù)制了之后再使用脓诡,不要直接操作l1 l2.
- 使用dummyHead可以省去提前處理第一個元素的問題无午,循環(huán)會比較簡單。
- 不得已要使用 left != null 這種方法
- 條件賦值看起來簡介祝谚。
官方代碼:
public ListNode addTwoNumbers(ListNode l1, ListNode l2)
{
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) curr.next = new ListNode(carry);
return dummyHead.next;
}
我的:
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode left = l1;
ListNode right = l2;
ListNode head = new ListNode(0);
ListNode cursor = head;
int carry = 0;
int sum = 0;
while (left != null || right != null) {
sum = cursor.val;
if (left != null) {
sum += left.val;
left = left.next;
}
if (right != null) {
sum += right.val;
right = right.next;
}
cursor.val = sum % 10;
carry = sum / 10;
if (left != null || right != null || carry != 0) {
cursor.next = new ListNode(carry);
cursor = cursor.next;
}
}
return head;
}
}