Add Two Numbers
LeetCode OJ 2: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.
思路:用链表模拟加法运算,注意加数和被加数的位数差异,处理好进位是本题解决的关键。
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int first = (l1->val + l2->val) % 10; int second = (l1->val + l2->val) / 10; ListNode * l3 = new ListNode(first); ListNode * head = l3; while(l1->next && l2->next) { first = (l1->next->val + l2->next->val + second) % 10; second = (l1->next->val + l2->next->val + second) / 10; l3->next = new ListNode(first); l3 = l3->next; l1 = l1->next; l2 = l2->next; } ListNode * temp = NULL; if(l1->next != NULL) temp = l1->next; else temp = l2->next; while(temp != NULL) { first = (temp->val + second) % 10; second = (temp->val + second) / 10; l3->next = new ListNode(first); temp = temp->next; l3 = l3->next; } if(second != 0) l3->next = new ListNode(second); return head; }