【LeetCode】002 Add Two Numbers
生活随笔
收集整理的這篇文章主要介紹了
【LeetCode】002 Add Two Numbers
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
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.
Input:?(2 -> 4 -> 3) + (5 -> 6 -> 4)
Output:?7 -> 0 -> 8
題解:
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 dummy(-1); 13 ListNode* pre = &dummy; 14 int carry = 0; 15 16 while (l1 || l2) { 17 int addend1 = l1 == nullptr ? 0 : l1->val; 18 int addend2 = l2 == nullptr ? 0 : l2->val; 19 int sum = addend1 + addend2 + carry; 20 ListNode* cur = new ListNode(sum % 10); 21 pre->next = cur; 22 pre = pre->next; 23 carry = sum / 10; 24 25 if (l1) 26 l1 = l1->next; 27 if (l2) 28 l2 = l2->next; 29 } 30 31 if (carry) { 32 ListNode* cur = new ListNode(carry); 33 pre->next = cur; 34 } 35 return dummy.next; 36 } 37 };
?
轉載于:https://www.cnblogs.com/Atanisi/p/6713957.html
總結
以上是生活随笔為你收集整理的【LeetCode】002 Add Two Numbers的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 部队四反一防指什么意思
- 下一篇: 非法持枪的枪的定义