您的位置:首页 > 其它

LeetCode(Add Two Number)

2014-04-17 03:01 323 查看
题目要求:

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
代码:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode* head;
int sum = l1->val + l2->val;
int carry = 0;
if(sum >= 10)
{
carry = 1;
sum -= 10;
}
head = new ListNode(sum);
l1 = l1->next;
l2 = l2->next;
ListNode* node = head;
while(l1 != NULL || l2 != NULL)
{
sum = 0;
if(l1 != NULL)
{
sum += l1->val;
l1 = l1->next;
}
if(l2 != NULL)
{
sum += l2->val;
l2 =l2->next;
}
sum += carry;
carry = sum / 10;
sum = sum % 10;
ListNode* tmp = new ListNode(sum);
node->next = tmp;
node = node->next;
}
if(carry == 1)
node->next = new ListNode(carry);
return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: