您的位置:首页 > 其它

LeetCode: Add two numbers

2013-03-15 14:19 489 查看
这题没什么难度,直接看代码吧

/**
* 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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: