leetcode:add two numbers

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.node

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8git

 

Hide Tags
 Linked List Math
Show Similar Problems
 
  這是一道簡單的鏈表操做實現高精度整數相加,奈何習慣了國內POJ在線編程詳細的中文問題描述和輸入輸出sample,至少前兩遍提交根本沒有徹底看懂題意,因此必定要提升英文閱讀量,簡單說說高精度整數相加算法,就是從鏈表頭遍歷到表尾,須要注意兩個number可能位數不同長,還有最後一次加操做結束後不要忘了進位。(扯點閒話,很是欣賞leetcode這種在線提交的風格,不一樣於ACM競賽之類須要完整的考慮輸入輸出,在這裏就像筆試現場,面試官等着你提交手寫的代碼,只要認真研究核心的算法就好了,上代碼…………)
 1 /**  2  * Definition for singly-linked list.  3  * struct ListNode {  4  * int val;  5  * ListNode *next;  6  * ListNode(int x) : val(x), next(NULL) {}  7  * };  8  */
 9 class Solution { 10 public: 11     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 12         ListNode *p1,*p2,*p3,*l3,*node; 13         int add,temp; 14         
15         p1 = l1; 16         p2 = l2; 17         add = temp = 0; 18         node = new ListNode(0); 19         temp += p1->val + p2->val; 20         if(temp>=10) 21         {temp = temp-10;add++;} 22         node->val = temp; 23         l3 = p3 = node; 24         p1 = p1->next; 25         p2 = p2->next; 26         while(p1!=NULL || p2!= NULL) 27  { 28             temp = add; 29             if(p1!=NULL) temp += p1->val; 30             if(p2!=NULL) temp += p2->val; 31             if(temp>=10) 32  { 33                 p3->next = new ListNode(temp-10); 34                 add=1; 35  } 36             else{ 37                 p3->next = new ListNode(temp); 38                 add=0; 39  } 40             if(p1!= NULL) p1 = p1->next; 41             if(p2!= NULL) p2 = p2->next; 42             p3 = p3->next; 43  } 44         if(add) 45  { 46             p3->next = new ListNode(add); 47  } 48        return l3; 49  } 50 };
相關文章
相關標籤/搜索