LeetCode---(2) Add Two Number
2015-05-11 16:12
330 查看
Problem
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
最终的进位需要注意
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
最终的进位需要注意
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if(l1==NULL&&l2==NULL) return NULL; ListNode *p=l1,*q=l2; ListNode* result=new ListNode(0); ListNode* current=result; int value=0; int carry=0; while(p!=NULL&&q!=NULL) { value=p->val+q->val+carry; current->next=new ListNode(value%10); current=current->next; carry=value/10; p=p->next; q=q->next; } while(p!=NULL) { value=p->val+carry; current->next=new ListNode(value%10); current=current->next; carry=value/10; p=p->next; } while(q!=NULL) { value=q->val+carry; current->next=new ListNode(value%10); current=current->next; carry=value/10; q=q->next; } if(carry!=0) current->next=new ListNode(1); current=result; result=result->next; delete current; return result; } };
相关文章推荐
- leetcode-Add Two Number
- leetcode add two number
- LeetCode-2.Add Two Number-Attemped using C
- LEETCODE: Add Two Number
- 【LeetCode】Merge Two Sorted Lists和Add TwoNumber解题报告
- [LeetCode By Python] 2 Add Two Number
- leetcode_add two number
- leetcode----Add Two Number 中学到的有关变量在内存中分配的问题
- LeetCode(Add Two Number)
- LeetCode--Add two Number II
- LeetCode Add Two Number
- [LeetCode]002-AddTwoNumber
- Add Two Number - Leetcode
- Leetcode练习-Add Two Number
- Leetcode 2. Add Two Number
- LeetCode: Add Two Number(已解原先出现的问题)
- LeetCode Interview Qustions: Add Two Number
- LeetCode笔记 -- Add Two Number
- LeetCode Online Judge 题目C# 练习 - Add two number
- LeetCode 2 Add Two Number