大数的乘法实现(C语言)

版权声明:转载请注明作者和出处。 https://blog.csdn.net/LQMIKU/article/details/79015306

大数的乘法实现(C语言)

  • 思想+程序

阅读之前注意:

本文阅读建议用时:25min
本文阅读结构如下表:

项目 下属项目 测试用例数量
思想+程序 1

思想+程序

思想:

  1. 用字符串来表示大数,并实现乘法
  2. 打印的时候注意符合阅读习惯(本程序未实现该功能)
    程序参考以下代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void count(char *str,int num,int position)//加法进位机制
{
    if (str[position] + num > '9')//如果当前超过9
    {
        str[position] = str[position] + num - 10;
        count(str, 1, position - 1);//进位
    }
    else
        str[position] = str[position] + num;
}

void add(char *str, int num, int position)//加法
{
    int res = num % 10;//余数,取得乘积的个位
    num = num / 10;//商,去掉乘积的个位
    count(str, res, position);//做单个数的加法
    if (num != 0)//如果乘积还有高位没加完
        add(str, num, position - 1);
}

void multi(char *strA, char *strB)//乘法
{
    int i = 0, j = 0;
    int sum = 0;
    int lenA = strlen(strA);
    int lenB = strlen(strB);

    char *strTmp = (char *)malloc((lenA + lenB + 1)*sizeof(char));//结果字符串
    int lenTmp = lenA + lenB;
    for (i = 0; i < lenTmp; i++)
        strTmp[i] = '0';
    strTmp[lenTmp] = '\0';

    int position = 0;
    for (i = lenB - 1; i >= 0; i--)
    {
        for (j = lenA - 1; j >= 0; j--)
        {
            sum = (strA[j] - 48)*(strB[i] - 48);//求单个位置-单个位置的乘积
            position = lenTmp - ((lenB - i) + (lenA - j) - 1);//计算乘积对应 结果字符串的位置
            add(strTmp, sum, position);//把乘积和字符串对应的位置做加法
        }
    }
    printf("%s\n", strTmp);
}

void main()
{
    char *str1 = "123456789";
    char *str2 = "987654321";
    multi(str1, str2);
    system("pause");
}

我的程序整体思想是把乘法和加法分离开来,按照乘法规则实现字符串的操作即可。事实上,问题还可以延伸到诸如:计算1*2*3*…*99*100的值,也算是一个经典面试题,有兴趣的话可以尝试一下哦,这个问题说不定还有更简洁的解法!1


  1. 问题延伸自“打印1到最大的n位数”——《剑指Offer 名企面试官精讲典型编程题》何海涛先生著.

猜你喜欢

转载自blog.csdn.net/LQMIKU/article/details/79015306
今日推荐