week_2_Add Two Numbers
来源:互联网 发布:PHP zend val 编辑:程序博客网 时间:2024/06/05 14:08
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
Solution
问题的本质如题目所示,即解决两个数的加法。很简单明晰,只不过数在表示形式上采用了逆序的链表。
容易想到的是将链表转换成相应整数,相加得到结果后再对应地用链表进行表示。
然而存在的问题是:数可能很大,单纯依靠系统内置的整数类型将产生溢出问题。
所以解决问题的关键在于处理大数加法。
大数加法的原理同样为简单地逐位进行相加,其算法思路如下:
① 声明三个长度为100的整形数组,分别用于对两个加数以及和进行存储。
② 三个数组全部初始化为0。
③ 依次将两个加数的链表内容转入两个数组进行存储,并相应的计算各自加数长度。
④ 初始化进位carry为0,以较大长度逐位进行相加,其中本位 = (num1+num2+carry)%10,进位 = (num1+num2+carry)/10。
⑤ 若循环结束后,进位不为0,则置当前和Sum前一位为进位值。
⑥ 对和数组以逆序形式采用链表进行输出,算法结束。
整个算法时间复杂度为O(n),运行结果如下:
- week_2_Add Two Numbers
- Two Numbers
- Two Sum & Add Two Numbers
- 题Two--Add Two Numbers
- 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
- Add Two Numbers
- 【leetcode】Add Two Numbers
- Parameter index out of range (2 > number of parameters, which is 1)
- 线性表的顺序存储——顺序表
- DB中Oracle with as 用法
- Java中的栈、堆和方法区
- 见贤思齐焉
- week_2_Add Two Numbers
- MyBatis--动态代理
- 【oracle】替代变量
- C语言实现冒泡排序算法(升序)
- 精雕细琢——全方位解析单例模式
- MySql函数
- 633. Sum of Square Numbers
- 数论基础(浅谈数论的部分实现)
- mysql引擎