【MEDIUM】Add Two Numbers

发布于:2019-03-22 19:31,阅读数:545,点赞数:0


# 问题 原题链接:[https://leetcode.com/problems/add-two-numbers/](https://leetcode.com/problems/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. Example: ``` Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. ``` # 分析过程 - 输入:两个链表 - 输出:相加的结果 - 思路:使用循环对应位相加即可,需要注意最后一位进位的处理。 # 解决方法 ```cpp class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { bool carry = false; ListNode root = ListNode(0); ListNode *tmp = &root; ListNode *la = l1; ListNode *lb = l2; while (la || lb) { int a = la ? la->val : 0; int b = lb ? lb->val : 0; int r = a + b + carry; carry = false; if (r >= 10) { r %= 10; carry = true; } tmp->next = new ListNode(r); tmp = tmp->next; la = la ? la->next : nullptr; lb = lb ? lb->next : nullptr; } if (carry) { tmp->next = new ListNode(1); } return root.next; } }; ```


评论:0条


返回列表

返回主页