zoukankan      html  css  js  c++  java
  • 大数乘法

    今天上课,实在无聊,手机上网的时候发现了一哥们提问如何实现大数的乘法,觉得挺有意思,查了点资料(华为某年的面试题就是如何实现大数的乘法),网上实现的方法很多,这里的思路是用数组每个元素存储一位数字,我把代码补全了,保证代码直接可以在编译器中通过... (DEV-C++ 5 编译通过)

    1 #include <iostream>
    2 #include <string.h>
    3  using namespace std;
    4
    5  void multiply(const char *a,const char *b);
    6
    7 int main()
    8 {
    9 //cout<<"hicjiajia"<<endl;
    10
    11 string num1,num2; // 初始状态用string来存储大数
    12 cout<<"现在,来两个大数吧! "<<endl;
    13 cin>>num1>>num2;
    14
    15 const char *p1=num1.c_str(); // 将string转为 const char *
    16 const char *p2=num2.c_str(); // 将string转为 const char *
    17 multiply(p1,p2);
    18
    19 system("pause");
    20 return 0;
    21 }
    22
    23 void multiply(const char *a,const char *b)
    24 {
    25 int i,j,ca,cb,*s;
    26 ca=strlen(a);
    27 cb=strlen(b);
    28 s=(int *)malloc(sizeof(int)*(ca+cb)); //分配存储空间
    29 for (i=0;i<ca+cb;i++) s[i]=0; // 每个元素赋初值0
    30
    31 for (i=0;i<ca;i++)
    32 for (j=0;j<cb;j++)
    33 s[i+j+1]+=(a[i]-'0')*(b[j]-'0');
    34
    35 for (i=ca+cb-1;i>=0;i--) // 这里实现进位操作
    36 if (s[i]>=10)
    37 {
    38 s[i-1]+=s[i]/10;
    39 s[i]%=10;
    40 }
    41
    42 char *c=(char *)malloc((ca+cb)*sizeof(char)); //分配字符数组空间,因为它比int数组省!
    43 i=0;while(s[i]==0) i++; // 跳过头部0元素
    44 for (j=0;i<ca+cb;i++,j++) c[j]=s[i]+'0';
    45 c[j]='\0';
    46 for (i=0;i<ca+cb;i++) cout<<c[i];
    47 cout<<endl;
    48 free(s);
    49 }
    50

    程序运行结果如图:

    大数乘法

  • 相关阅读:
    Python实现二分法查找
    Python实现冒泡排序
    issues:closeForm字段默认值设置,roo创建应用的默认语言设置
    howto:IEDA 中运行Maven项目
    将繁体中文国际化文件,变为简体中文国际化文件
    JasperServer安装XP异常解决
    note:maven 简介
    note:addon开发基础知识
    issues:close 云端 STS 启动报找不到 jdk
    小程序ios设置map圆角不生效的问题解决方案
  • 原文地址:https://www.cnblogs.com/hicjiajia/p/1836337.html
Copyright © 2011-2022 走看看