[LeetCode 2] Add Two Numbers Solution
2014-04-13 05:23
633 查看
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
Idea: The solution is straightforward.
Check the NULL case
Add the values together, if sum is larger than 10, then, we need a carry bit to record the value
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Idea: The solution is straightforward.
Check the NULL case
Add the values together, if sum is larger than 10, then, we need a carry bit to record the value
/** * 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) return l2; if(l2 == NULL) return l1; int count = 0; // used for carry bit ListNode *temp = new ListNode(-1); //declare a head node ListNode *head = temp; ListNode *h1 = l1; ListNode *h2 = l2; while(h1 != NULL || h2 != NULL){ int v1 = (h1 != NULL ? h1->val: 0); //it is a good ideas to get the value int v2 = (h2 != NULL ? h2->val: 0); int value = v1 + v2 + count; ListNode *node = new ListNode(value % 10); count = value / 10; temp->next = node; temp = temp->next; h1 = (h1 != NULL ? h1->next : NULL); // it is h1 != NULL, but not h1->next !=NULL h2 = (h2 != NULL ? h2->next : NULL); } if(count > 0){ temp->next = new ListNode(1); } ListNode *t = head; //delete the first head node head = head->next; delete t; return head; } };
相关文章推荐
- LeetCode #2 Add Two Numbers Cpp Solution
- solution about leetcode problem 2 add Two Numbers
- [LeetCode] Add Two Numbers, Solution
- Leetcode 2. Add Two Numbers The Solution of Python and Javascript
- leetcode-solution C++【2】---add two numbers
- leetcode: add two numbers , hash search solution, java. O(n)
- [LeetCode] Add Two Numbers, Solution
- LeetCode第四题,Add Two Numbers
- LeetCode-Add Two Numbers
- Leetcode解题-链表(2.2.1)AddTwoNumbers
- 【刷题史】leetcode-Add Two Numbers
- Leetcode_Add Two Numbers
- leetcode 2 Add Two Numbers
- leetcode:Add Two Numbers---------java源码
- LeetCode Add Two Numbers
- Leetcode 2-Add two numbers
- [LeetCode] Add Two Numbers
- 【Leetcode】【python】Add Two Numbers
- Add Two Numbers ---LeetCode
- [LeetCode] Add Two Numbers(C++)