[leetCode]Add Two Numbers
想当初写过C的大数加减法,恍如隔世。
1 #include <iostream> 2 using namespace std; 3 struct ListNode { 4 int val; 5 ListNode *next; 6 ListNode(int x) : val(x), next(NULL) {} 7 }; 8 class Solution { 9 public: 10 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 11 if(l1 == NULL) return l2; 12 if(l2 == NULL) return l1; 13 ListNode *head,*tail; 14 head = tail = NULL; 15 bool isCarry = false; 16 while(l1 != NULL && l2 != NULL){ 17 int digit = l1->val + l2->val; 18 if(isCarry) digit++; 19 if(digit >= 10){ 20 digit %= 10; 21 isCarry = true; 22 }else{ 23 isCarry = false; 24 } 25 if(head == NULL) head = tail = new ListNode(digit); 26 else{ 27 tail->next = new ListNode(digit); 28 tail = tail->next; 29 } 30 l1 = l1->next; 31 l2 = l2->next; 32 } 33 ListNode *cur = NULL; 34 if(l1 == NULL && l2 == NULL){ 35 if(isCarry) tail->next = new ListNode(1); 36 return head; 37 } 38 else if(l1 == NULL) cur = l2; 39 else if(l2 == NULL) cur = l1; 40 tail->next = cur; 41 while(isCarry){ 42 cur->val +=1; 43 if(cur->val < 10) isCarry = false; 44 else{ 45 cur->val %= 10; 46 if(cur->next == NULL) cur->next = new ListNode(0); 47 cur = cur->next; 48 } 49 } 50 return head; 51 } 52 };
艰难的成长