LeetCode 第二道题 两数相加
给定两个非空链表来代表两个非负整数,位数按照逆序方式存储,它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
题目思路说明,请参考[https://leetcode-cn.com/problems/add-two-numbers/solution/]
java
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode p = result;
int carray = 0;
while ((l1 != null) || (l2 != null) || carray != 0) {
int sum = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carray;
carray = sum / 10;
p.next = new ListNode(sum % 10);
p = p.next;
l1 = l1 != null ? l1.next : l1;
l2 = l2 != null ? l2.next : l2;
}
return result.next;
}
C++
class Solution
{
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
{
ListNode preHead(0), *p = &preHead;
int carry = 0; ///carry的作用:记录两个链表相加后的高位(进位);
while(l1||l2||carry)
{
int sum = (l1?l1->val:0)+(l2?l2->val:0)+(carry);
carry = sum/10;
p->next = new ListNode(sum%10);
p = p->next;
l1 = l1?l1->next:l1;
l2 = l2?l2->next:l2;
}
return preHead.next;
}
};
python
class Solution(object):
def addTwoNumbers(self, l1, l2):
ptrHead = ListNode(0)
p = ptrHead
carry = 0
while((l1 is not None) or (l2 is not None) or carry != 0):
sum = (l1.val if (l1 is not None) else 0) + (l2.val if (l2 is not None) else 0) + carry
carry = int(sum/10)
p.next = ListNode(sum % 10)
p = p.next
l1 = l1.next if l1 is not None else l1
l2 = l2.next if l2 is not None else l2
return ptrHead.next