LeetCode: Add two numbers
2013-03-15 14:19
489 查看
这题没什么难度,直接看代码吧
Java:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* dfs(ListNode *l1, ListNode *l2, int carry) { if (!l1 && !l2) { if (!carry) return NULL; else { ListNode* tmp = new ListNode(carry); return tmp; } } if (!l1) { int sum = l2->val + carry; ListNode* tmp = new ListNode(sum%10); carry = sum/10; tmp->next = dfs(l1, l2->next, carry); return tmp; } if (!l2) { int sum = l1->val + carry; ListNode* tmp = new ListNode(sum%10); carry = sum/10; tmp->next = dfs(l1->next, l2, carry); return tmp; } if (l1 && l2) { int sum = l1->val + l2->val + carry; ListNode* tmp = new ListNode(sum%10); carry = sum/10; tmp->next = dfs(l1->next, l2->next, carry); return tmp; } } ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { // Start typing your C/C++ solution below // DO NOT write int main() function int carry = 0; ListNode *ret = dfs(l1, l2, carry); return ret; } };
Java:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { return addTwoNumbersWithCarry(l1, l2, 0); } private ListNode addTwoNumbersWithCarry(ListNode l1, ListNode l2, int carry) { if (l1 == null && l2 == null) { if (carry > 0) { return new ListNode(carry); } else { return null; } } else if (l1 == null) { int num = l2.val + carry; ListNode newNode = new ListNode(num % 10); newNode.next = addTwoNumbersWithCarry(l1, l2.next, num / 10); return newNode; } else if (l2 == null) { int num = l1.val + carry; ListNode newNode = new ListNode(num % 10); newNode.next = addTwoNumbersWithCarry(l1.next, l2, num / 10); return newNode; } else { int num = l1.val + l2.val + carry; ListNode newNode = new ListNode(num % 10); newNode.next = addTwoNumbersWithCarry(l1.next, l2.next, num / 10); return newNode; } } }
相关文章推荐
- Leetcode Add Two Numbers
- LeetCode——2. Add Two Numbers
- [Leetcode]Add Two Numbers
- LeetCode_Add Two Numbers
- LeetCode Algorithm Add Two Numbers
- [leetcode]2. Add Two Numbers
- Add Two Numbers -- leetcode
- 2015-05-23 LeetCode 2: Add Two Numbers 个人总结
- [leetcode] 2. Add Two Numbers
- 【Leetcode】Add Two Numbers
- leetcode 2. Add Two Numbers python实现的理解,结点,单链表的应用,大数,进位的问题
- (leetcode)2. 两个链表相加Add Two Numbers--Java
- Leetcode 第二章线性表--2.2 单链表--2.2.1 add two numbers--2017/7/25
- Linked List -- Leetcode problem 2. Add Two Numbers
- LeetCode : 2 Add Two Numbers C++
- [LeetCode] Add Two Numbers
- LeetCode || Add Two Numbers
- LeetCode -- Add Two Numbers
- Leetcode 2. Add Two Numbers The Solution of Python and Javascript
- LeetCode2——Add Two Numbers(两个链表中的数字相加,形成新链表)