在这一讲中,我们主要讲解关于加法的相关题目。
leetcode#2Add 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 - 8Explanation: 342 + 465 = 807.
二、思路这道题就是模拟加法的过程,熟悉加法器的同学都知道这个过程是什么样子的。只需要设置一个进位就可以了。但是这里需要考虑一个问题,就是如果两个数不一般长的时候,如何处理。另外一个要注意的地方是如果最后的和比原来最长的数还要进位,该如何处理。
三、代码
leetcode#445Add Two Numbers II一、题目描述You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.Follow up:What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 - 2 - 4 - 3) + (5 - 6 - 4)Output: 7 - 8 - 0 - 7
二、思路这道题难就难在不能够让列表反转,不然的话,就可以使用上面题目了。因为链表反转是比较容易操作的。但是可以使用其他隐性的反转,比如使用栈来表示倒序,是一个非常不错的方法。三、代码
小结本节我们只介绍了2个题目,收获如下:1.一定弄清楚本质,然后使用计算机来进行模拟。这也是计算机诞生之初所做的事情。2.一定要熟悉常用的数据结构,比如链表的操作(逆指、快慢指针、插入、删除、合并等),队列和栈,树(二叉检索树,树的插入和删除,深度优先广度优先搜索)以及HashMap等。
本人技术博客同步更新,欢迎关注:刘炫320的博客_CSDN博客-算法编程习题解答(java版),机器学习习题集,leetcode领域博主