Add Two Numbers题解
来源:互联网 发布:testv淘宝店搜不到 编辑:程序博客网 时间:2024/05/17 18:16
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
题目显得很简单 就是将俩串链表相加 然后有进位的
在算法上 直接的对两个链表进行 扫描 将对应的 数字相加 得到个位与十位 十位作为进位 加到下一位内, 而一旦有一个链表先用完 就作为剩下的数字为0处理。
但是,在链表的实现上比较麻烦,容易出现错误,还有就是判断结束的条件也是有点麻烦,因为如果两个链表都被用完,但是还有进位的话,这个进位也应该被作为下一个节点的值。
所以 解决代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode node(0); ListNode *solution = &node;int temp,a,b,x,y;b=0;while(l1||l2||b){if(l1){ x=l1->val;l1 = l1->next; }elsex=0;if(l2){ y=l2->val;l2 = l2->next; }elsey=0;temp = x + y + b;a = temp%10;b = temp/10;solution -> next = new ListNode(a); solution = solution -> next;}return node.next; }};
主要就是在判断结束条件和当一边链表结束后 将其加数作为零的处理 总体来说算是简单的题目。
0 0
- Add Two Numbers题解
- LeetCode题解:Add Two Numbers
- LeetCode题解:Add Two Numbers
- leetcode2 Add Two Numbers题解
- 2. Add Two Numbers 题解
- [LeetCode] Add Two Numbers题解
- LeetCode 题解(26): Add Two Numbers
- LeetCode题解 || Add Two Numbers 问题
- [Leetcode题解]002 Add Two Numbers
- LeetCode题解--2. Add Two Numbers
- 2. Add Two Numbers : LeetCode 题解
- LeetCode题解:2. Add Two Numbers
- leetcode 题解 2. Add Two Numbers
- Leetcode题解 - 2. Add Two Numbers
- LeetCode题解-2-Add Two Numbers
- LeetCode Algorithms 2. Add Two Numbers 题解
- LeetCode445.Add Two Numbers II题解
- LeetCode 2. Add Two Numbers 题解
- UI框架总结
- java初始化的顺序
- 最长公共子串 最长公共子序列
- 系统设计——关于数据库表设计的感悟
- poj1681(高斯消元)
- Add Two Numbers题解
- Partition Magic硬盘分区免费版
- ROS工作空间与程序包的创建
- 教你步步为营掌握自定义 View
- ios开发中最简单的tableview使用一
- Head First Design Patterns 阅读笔记之三: Decorator Pattern
- Java RESTful框架的性能比较
- js动态生成html,获取点击的监控事件写法
- qdu Mathematics and Geometry(思维题)