链表实现任意精度整数运算包,统计 的各字符数量,C 语言实现方法。题目来自《数据结构与算法分析:C 语言描述》第三章课后第 9 题。
问题描述
3.9. 编写任意精度整数运算包。要使用类似于多项式运算的方法。计算在 内数字 0 到 9 的分布。
3.9. Write an arbitrary-precision integer arithmetic package. You should use a strategy similar to polynomial arithmetic. Compute the distribution of the digits 0 to 9 in .
随书没有附本题答案,网上几乎没搜到相关解答,仅有的一些解答也存在问题。刚好自己写一版。
思考要点
-
题 3.4-3.8,已经逐步实现了单链表表示多项式,并执行了多项式加法,3 种思路的多项式乘法,和多项式幂运算。在此基础上,根据提示,把任何精度十进制本质上可以看成 10 的不同次幂的多项式,即可用现成的算法执行整数运算。
-
最直接的方法就是把 循环乘 4000 次。二分法可以减少时间复杂度,按下不表。
-
需要注意的是进位,在运算中直接进位是最好的,但是为了基本照抄前面的算法,我在每次运算完成后才进位。
-
解决进位时前一项指针的记录问题的方法有,
-
编写 FindPrevious 函数,时间复杂度较大;
-
改成链表从小到大记录,简单直接,但是若在题目要求之外需要从大到小打印,可能存在递归栈溢出的风险;
-
将单链表改成双链表。
-
这里采用第三种。
算法实现
big_integer.h
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#ifndef _Big_integer_H
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode BigInt;
typedef PtrToNode Position;
int IsLast(Position P, BigInt BI);
void Insert(int c, int e, BigInt BI, Position P);
void PrintBigInt(BigInt BI);
void BigIntConstructor(int *C, int *E, int N, BigInt BI);
BigInt BigIntAdd(BigInt BI1, BigInt BI