LeetCode题解 第二周
来源:互联网 发布:网络语言99是什么意思 编辑:程序博客网 时间:2024/06/04 18:19
1.Add Two Numbers
https://leetcode.com/problems/add-two-numbers/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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8
Difficulty:Medium
Explanation:
1、两个链表中的每个节点依次相加,最后将所得的结果储存在一个新的链表之中。对于这个题目,可以参照数字电路里面的加法器的设计思路,让两个数的每位上的数字和进位相加(如果前一个数位上的数字相加没有进位的话进位为零),如果结果大于10则设置进位为1,否则设置进位为0,然后把计算结果的个位数储存到结果链表。如此循环计算,直至两个链表中的每个数位都进行了相加操作。
code:
class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {int carry;ListNode* temp1 = l1;ListNode* temp2 = l2;ListNode* solution = new ListNode(0);ListNode* temp3 = solution;carry = 0;while (temp1 != NULL||temp2 != NULL){int sum;if (temp1 == NULL){sum = temp2->val + carry;}else if (temp2 == NULL){sum = temp1->val + carry;}else{sum = temp1->val + temp2->val + carry;}temp3->val = sum % 10;carry = sum / 10; if(temp1!=NULL) { temp1 = temp1->next; } if(temp2!=NULL) {temp2 = temp2->next; }if (temp1 != NULL||temp2 != NULL){temp3->next = new ListNode(0);temp3=temp3->next;}} if(carry==1) { temp3->next=new ListNode(1); }return solution;}};
Attention:需要注意的是,进行相加操作的两个链表可能长度并不相同,所以分情况讨论每次相加时是不是两个链表都已经到达了尾部。
阅读全文
0 0
- LeetCode题解 第二周
- #第二周1000题解#
- #第二周1001题解#
- #第二周1002题解#
- #第二周1003题解#
- Leetcode第二题解题java实现
- LeetCode题解 第三周
- LeetCode题解 第五周
- LeetCode题解 第六周
- LeetCode题解 第七周
- LeetCode题解 第八周
- LeetCode题解 第九周
- LeetCode题解 第十周
- LeetCode题解 第十二周
- LeetCode题解 第十三周
- LeetCode题解 第十五周
- LeetCode题解 第十六周
- 第二题解
- Static
- 太空大战1.0
- Java解析和构造XML数据
- 文件上传的细节问题
- 最后的约定
- LeetCode题解 第二周
- hdu-1541-树状数组-java
- Linux进阶之 tar 命令
- loadrunner Web_类函数之web_link()
- 第二周项目二——程序的多文件组织
- 扩展欧几里得算法
- tensorflow实战2:实现mnist 单层cnn分类
- 第二周LeetCode算法题
- 今日头条条目联动