You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode p = l1, q = l2, curr = dummyHead; int carry = 0; while (p != null || q != null) { int x = (p != null) ? p.val : 0; //节点存在,则为节点值;节点为空,则置为0 int y = (q != null) ? q.val : 0; int sum = carry + x + y; //两数相加,且加上低位的进位 carry = sum / 10; //进位 curr.next = new ListNode(sum % 10); curr = curr.next; if (p != null) p = p.next; if (q != null) q = q.next; } if (carry > 0) { curr.next = new ListNode(carry); //最高位 } return dummyHead.next; }
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* pRoot = NULL;
do {
if (l1 == NULL) {
pRoot = l2;
break;
}
if (l2 == NULL) {
pRoot = l1;
break;
}
int sum = l1->val + l2->val;
int digit = sum % 10; //如sum=12,digit=2
int carry = sum / 10; //如sum=12,进位等于1
pRoot = new ListNode(digit);
ListNode* pTail = pRoot;
l1 = l1->next;
l2 = l2->next;
while (l1 != NULL || l2 != NULL) {
int sum = ((l1 != NULL) ? l1->val : 0) + ((l2 != NULL) ? l2->val : 0) + carry;
int digit = sum % 10;
l1 = l1 != NULL ? l1->next : NULL;
l2 = l2 != NULL ? l2->next : NULL;
}
if (carry == 1) {
ListNode* pNew = new ListNode(carry);
pTail->next = pNew;
}
} while (false);
return pRoot;
}
};
原文:http://www.cnblogs.com/hozhangel/p/7726412.html