Leecode
使用虚拟头结点进行处理,要注意计算到最后考虑进位是否还有数值
这里有一个效率比较,直接使用三目运算符效率比进行除法效率更高
// carry = total / 10;
carry = total > 9 ? 1 : 0;
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode dummyHead = new ListNode(0);
ListNode last = dummyHead;
// 进位
int carry = 0;
while (l1 != null || l2 != null) {
int v1 = 0;
if (l1 != null) {
v1 = l1.val;
l1 = l1.next;
}
int v2 = 0;
if (l2 != null) {
v2 = l2.val;
l2 = l2.next;
}
int total = v1 + v2 + carry;
// carry = total / 10; 直接使用三目运算符效率更高
carry = total > 9 ? 1 : 0;
last.next = new ListNode(total % 10);
last = last.next;
}
if (carry > 0) last.next = new ListNode(carry);
return dummyHead.next;
}











网友评论