leetcode [002] : Add Two Numbers
2015-09-10 20:36
579 查看
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
1、最开始看错题了,还自己写了一个reverse linked list
2、题目是说原数字是倒过来存储的,所以上面的示例Input是 342 + 465,答案是807,Output也是倒过来存放的
3、也就是说题目已经把数字从个位对齐了,得到的Ouput也是不需要再倒序的,只需要挨着加上去就行
4、主要的伪代码为 iNewNum = iNumber1 + iNumber2 + iCarryFlags
5、每次如果iNewNum大于等于10,那么iCarryFlag设置为1,iNewNum减小10,否则设置为0
6、注意边界情况,也就是第一个linked list和第二个linked list都加完了,但这个时候iCarryFlag不为0,说明还要向上进一位
7、所以循环条件为 while (第一个链表当前节点不为NULL || 第二个链表当前节点不为NULL || iCarryFlag);
源代码如下:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
1、最开始看错题了,还自己写了一个reverse linked list
2、题目是说原数字是倒过来存储的,所以上面的示例Input是 342 + 465,答案是807,Output也是倒过来存放的
3、也就是说题目已经把数字从个位对齐了,得到的Ouput也是不需要再倒序的,只需要挨着加上去就行
4、主要的伪代码为 iNewNum = iNumber1 + iNumber2 + iCarryFlags
5、每次如果iNewNum大于等于10,那么iCarryFlag设置为1,iNewNum减小10,否则设置为0
6、注意边界情况,也就是第一个linked list和第二个linked list都加完了,但这个时候iCarryFlag不为0,说明还要向上进一位
7、所以循环条件为 while (第一个链表当前节点不为NULL || 第二个链表当前节点不为NULL || iCarryFlag);
源代码如下:
#include <iostream> #include <string> #include <vector> #include <unordered_map> using namespace std; 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) return l2; if (l2 == NULL && l1) return l1; ListNode * pCur1 = l1; ListNode * pCur2 = l2; ListNode * pResult = NULL; ListNode * pResultTail = NULL; ListNode * pNew = NULL; int iCarryFlag = 0; while (pCur1 || pCur2 || iCarryFlag) { pNew = new ListNode(0); if (pCur1 && pCur2) { pNew->val = pCur1->val + pCur2->val + iCarryFlag; } else if (pCur1) { pNew->val = pCur1->val + iCarryFlag; } else if (pCur2) { pNew->val = pCur2->val + iCarryFlag; } else { pNew->val = iCarryFlag; } iCarryFlag = 0; if (pNew->val >= 10) { pNew->val = pNew->val - 10; iCarryFlag = 1; } pNew->next = NULL; if (pResult == NULL) { pResult = pNew; pResultTail = pNew; } else { pResultTail->next = pNew; pResultTail = pNew; } if (pCur1) pCur1 = pCur1->next; if (pCur2) pCur2 = pCur2->next; } return pResult; } }; int main() { system("pause"); return 0; }
相关文章推荐
- android Activity launch mode 知识点总结
- POJ 2992 求组合数的因子个数
- ARM嵌入式开发中虚拟机中ubuntu的配置
- Handler相关的弱引用
- 【leetcode每日一题】100.same treet
- hdu 5384 Danganronpa(基础AC自动机)
- HotSpot Builder Utility安装指南
- 面向对象实例编程
- hdu1059
- CoreData
- 系统维护之CCleaner Pro 5.09 便携版|优秀系统清理工具
- Oracle 学习之 性能优化(十三) 索引
- MySql性能优化之分析命令
- Spring-MVC开发之全局异常捕获全面解读
- 用UITextView加载rtfd文件
- bundle的理解笔记
- Genymotion unable to load virtualbox engine 解决办法
- 效率相关笔记
- poj 1523 SPF 图论基础 图的割点
- 音乐播放器