LeetCode-----第二题-----两数相加
生活随笔
收集整理的這篇文章主要介紹了
LeetCode-----第二题-----两数相加
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2. 兩數(shù)相加
難度:中等
給出兩個?非空?的鏈表用來表示兩個非負(fù)的整數(shù)。其中,它們各自的位數(shù)是按照?逆序?的方式存儲的,并且它們的每個節(jié)點(diǎn)只能存儲?一位?數(shù)字。
如果,我們將這兩個數(shù)相加起來,則會返回一個新的鏈表來表示它們的和。
您可以假設(shè)除了數(shù)字 0 之外,這兩個數(shù)都不會以 0?開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 輸出:7 -> 0 -> 8 原因:342 + 465 = 807?
題目解析:
? ? ? ?主要考慮兩個問題,一個是兩個鏈表長短不一樣,另一個是最后的進(jìn)位還存在,最后還需要構(gòu)建一個節(jié)點(diǎn)存放
?
參考代碼:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {if (l1 == NULL && l2 != NULL)return l2;if (l1 != NULL && l2 == NULL)return l1;if (l1 == NULL && l2 == NULL)return NULL;int temp = 0;//進(jìn)位和ListNode* head = new ListNode(0);ListNode* pMove = head;while (l1 != NULL && l2 != NULL){temp += l1->val + l2->val;ListNode* new_node = new ListNode(temp % 10);pMove->next = new_node;pMove = pMove->next;temp /= 10;l1 = l1->next;l2 = l2->next;}while (l1 != NULL){temp += l1->val;ListNode* new_node = new ListNode(temp % 10);temp /= 10;pMove->next = new_node;pMove = pMove->next;l1 = l1->next;}while (l2 != NULL){temp += l2->val;ListNode* new_node = new ListNode(temp % 10);temp /= 10;pMove->next = new_node;pMove = pMove->next;l2 = l2->next;}if (temp > 0){ListNode* new_node = new ListNode(temp % 10);pMove->next = new_node;}return head->next;} };總結(jié)
以上是生活随笔為你收集整理的LeetCode-----第二题-----两数相加的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ERROR in xxx.js from
- 下一篇: 教育培训app开发迅速成长的原因是?未来