2. 两数相加
最近更新:2025-03-12 | 字数总计:143 | 阅读估时:1分钟 | 阅读量:次
- 解析
- 迭代法
Problem: 2. 两数相加
解析
迭代法
简单的数学模拟,几分钟搞定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode *node1 = l1; ListNode *node2 = l2; int base = 0, carry = 0, num1 = 0, num2 = 0; ListNode *node = new ListNode(-1); ListNode *answer = node; while (node1 != nullptr || node2 != nullptr) { num1 = 0, num2 = 0; if (node1 != nullptr) { num1 = node1->val; node1 = node1->next; } if (node2 != nullptr) { num2 = node2->val; node2 = node2->next; } base = (num1 + num2 + carry) % 10; node->next = new ListNode(base); node = node->next; carry = (num1 + num2 + carry) / 10; } if(carry!=0){ node->next =new ListNode(carry); } return answer->next; } };
|