# LCP002 LeetCode 2. Add Two Numbers

188人阅读 评论(1)

Total Accepted: 147076 Total Submissions: 627191 Difficulty: Medium

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

Subscribe to see which companies asked this question

class Solution {
public:
ListNode* add(ListNode* l1, ListNode* l2, bool carryBit)
{
if (l1 != NULL || l2 != NULL)
{
if (l1 == NULL)
{
l1 = new ListNode (0);
}
if (l2 == NULL)
{
l2 = new ListNode (0);
}
l1->val += l2->val;
if (carryBit)
{
l1->val += 1;
}
carryBit = l1->val / 10;
l1->val %= 10;
}
else if (carryBit)
{
ListNode* newBit = new ListNode (1);
return newBit;
}
return l1;
}
{
return l1;
}
};

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
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);
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：17865次
• 积分：541
• 等级：
• 排名：千里之外
• 原创：25篇
• 转载：4篇
• 译文：11篇
• 评论：8条
文章分类
阅读排行
最新评论