用链表模拟大整数加法运算
2014-04-10 22:52
381 查看
例如:9>9>9>NULL + 1>NULL =>
1>0>0>0>NULL
肯定是使用递归啦,不然没办法解决进位+1问题,因为这时候要让前面的节点加1,而我们的单链表是永远指向前的。
此外对于999+1=1000,新得到的值的位数(4位)比原来的两个值(1个1位,1个3位)都多,所以我们将表头的值设置为0,如果多出一位来,就暂时存放到表头。递归结束后,如果表头为1,就在新的链表外再加一个新的表头。
//head1 length > head2, so M > N
public static int Add(Link head1, Link head2, ref Link newHead, int M, int N)
{
// goto the end
if (head1 == null)
return 0;
int temp = 0;
int result = 0;
newHead = new Link(null, 0);
if (M > N)
{
result = Add(head1.Next, head2, ref newHead.Next, M - 1, N);
temp = head1.Data + result;
newHead.Data = temp % 10;
return temp >= 10
}
else // M == N
{
result = Add(head1.Next, head2.Next, ref newHead.Next, M - 1, N - 1);
temp = head1.Data + head2.Data + +result;
newHead.Data = temp % 10;
return temp >= 10
}
}
这里假设head1比head2长,而且M、N分别是head1和head2的长度。
1>0>0>0>NULL
肯定是使用递归啦,不然没办法解决进位+1问题,因为这时候要让前面的节点加1,而我们的单链表是永远指向前的。
此外对于999+1=1000,新得到的值的位数(4位)比原来的两个值(1个1位,1个3位)都多,所以我们将表头的值设置为0,如果多出一位来,就暂时存放到表头。递归结束后,如果表头为1,就在新的链表外再加一个新的表头。
//head1 length > head2, so M > N
public static int Add(Link head1, Link head2, ref Link newHead, int M, int N)
{
// goto the end
if (head1 == null)
return 0;
int temp = 0;
int result = 0;
newHead = new Link(null, 0);
if (M > N)
{
result = Add(head1.Next, head2, ref newHead.Next, M - 1, N);
temp = head1.Data + result;
newHead.Data = temp % 10;
return temp >= 10
}
else // M == N
{
result = Add(head1.Next, head2.Next, ref newHead.Next, M - 1, N - 1);
temp = head1.Data + head2.Data + +result;
newHead.Data = temp % 10;
return temp >= 10
}
}
这里假设head1比head2长,而且M、N分别是head1和head2的长度。
相关文章推荐
- 用链表模拟大整数加法运算
- 11.用链表模拟大整数加法运算
- 2.4-链表模拟整数加法(same in LeetCode)
- 实现任意长的整数进行加法运算的演示程序
- Problem A: 大整数的加法运算
- 多项式加法运算 使用链表实现
- 多项式乘法与加法运算(链表实现)
- 实现超大整数(超过long长度范围)的加法运算
- 大整数运算之 大整数加法、减法、乘法
- 华为机试——超大整数加法运算
- 整数大数模拟 高精度加法 高精度减法 高精度乘法 高精度除法 c/c++ java
- LeetCode 2 链表操作(带进位的加法运算)
- 链表的应用 —— 多项式运算(加法+乘法)
- PAT 一元多项式的乘法与加法运算(20)(模拟计算过程)
- 大整数的加法运算
- 大整数运算之 大整数加法、减法、乘法
- 整数的加法运算
- 大型整数运算:加法, 减法, 乘法
- 大整数的加法和乘法运算
- 算法(求对输入的N个数进行加法或减法运算,得到最小的正整数的组合.)