Add Two Numbers 解法
来源:互联网 发布:radiohead知乎 编辑:程序博客网 时间:2024/06/09 20:13
Add Two Numbers 解法
第一周题目
难度:Media
LeetCode题号:2
题目
Description:
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.
Example1:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思考
先将两个链表尾部填充0使得两个链表的长度一样长
然后对每一位模拟加法,addNum为当前同一位两个数的和,remainder是和的个位数,是结果中此位的数字,carry是和的十位数,是进位,用于下一位的加法。
循环到最后时,carry有两种情况,0或1,当carry为1时不处理,当carry为0时,把前一位的next设为null
代码
class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { // 扩充链表,填0,使得两个链表一样长 ListNode* l1_expand = l1; ListNode* l2_expand = l2; while (l1_expand->next != NULL && l2_expand->next != NULL) { l2_expand = l2_expand->next; l1_expand = l1_expand->next; } if (l1_expand->next == NULL) { while (l2_expand->next != NULL) { l2_expand = l2_expand->next; ListNode* temp = new ListNode(0); l1_expand->next = temp; l1_expand = l1_expand->next; } } else { while (l1_expand->next != NULL) { l1_expand = l1_expand->next; ListNode* temp = new ListNode(0); l2_expand->next = temp; l2_expand = l2_expand->next; } } ListNode * rel_index = new ListNode(0); ListNode * result = rel_index; ListNode * old_rel_index; int carry = 0, remainder = 0; while (l1 != NULL && l2 != NULL) { int addNum = carry + l1->val + l2->val; remainder = addNum % 10; carry = addNum / 10; rel_index->val = remainder; old_rel_index = rel_index; rel_index->next = new ListNode(0); rel_index = rel_index->next; l1 = l1->next; l2 = l2->next; } rel_index->val = carry; if (carry == 0) { old_rel_index->next = NULL; } return result; }};
阅读全文
0 0
- Add Two Numbers 解法
- Add Two Numbers问题及解法
- LeetCode 2. Add Two Numbers python 解法
- Add Two Numbers II问题及解法
- LeetCode Add Two Numbers 之JavaScript 多种解法
- Add two numbers & Add binary
- LeetCode: Add Two Numbers
- Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode4: Add Two Numbers
- Leetcode : Add Two Numbers
- 数组去重
- VS2015编译32位Opencv310(动态库+静态库,文末有下载链接)
- git版本跟踪
- Mysql 锁表 for update (引擎/事务)
- 科技创新才能引领未来
- Add Two Numbers 解法
- GCC和G++区别
- ArrayList源码分析 JDK1.8
- 用hadoop实现倒排索引简单实例
- 05-python中函数的简单使用
- ConstraintLayout 学习笔记
- 共享游艇加入了共享家族
- 一些常见的专业英语词汇(01)
- Tesseract入门-VS2015下调用Tesseract4.0 +win7 64位系统