大数乘法

来源:互联网 发布:路书app 知乎 编辑:程序博客网 时间:2024/04/29 13:07
#include <iostream>#include <assert.h>#include <string.h>using namespace std;char* resver (char* dest)       //字符串翻转{        char *start = dest;        char *left = dest;        char ch;        while (*dest++)                                 ;         dest -= 2;        while (left < dest)        {                ch = *left;                *left++ = *dest;                *dest-- = ch;        }  return (start);}char* maxmlu(char* num1, char* num2, char* num3 )       {      assert(num1 && num2 && num3);  if (num1[0] == '0' || num2[0] == '0' )  {  num3[0] = '0';  return num3;  }  int len1 = strlen(num1);  int len2 = strlen(num2);  resver(num1);  resver(num2);  memset(num3,0,sizeof(char)*127);  for (int i = 0; i<len1; i++)  {  for (int j = 0; j<len2; j++)  {  short temp1 = num1[i] - '0';  short temp2 = num2[j] - '0';  short temp3 = temp1*temp2;  num3[i+j] += temp3;  int count = 0;  while (num3[i+j+count] >9)       //如果大于9进位  {  num3[i+j+1+count] += (num3[i+j+count]/10);  num3[i+j+count] = num3[i+j+count]%10;  count++;  }  }  }  for (int i = 0; i<=len1+len2; i++)  {  num3[i] += '0';  }  num3[len1+len2] = '\0';  resver(num3);              //将3个字符数组翻转回来  resver(num1);  resver(num2);        int k = 0;  while (num3[k] == '0')      //计算前面是0的数目   k++;  memmove(num3,&num3[k],(126-k));   //将前面为0的部分覆盖        return num3;}int main(){char num1[64] = "";        //乘数最多为63位最后一位放'\0'char num2[64] = "";char ret[127]={0};         //最大的结果为126 最后一位放'\0'cout<<"输入乘数一:"<<endl;cin.getline(num1,64);cout<<"输入乘数二:"<<endl;cin.getline(num2,64);maxmlu(num1,num2,ret);cout<<num1<<"*"<<num2<<"="<<ret<<endl; return  0;}

用字符数组可以存放更多位数,

如1234*5678,就是用 8 *1234 + 70* 1234+ 600*1234 + 5000*1234 ,  8*1234 为8*4+8*30+8*200+8*1000,

所以将两个字符串翻转然后逐位相乘,如果大于10进位。 我写的这个程序没有考虑负数相乘,还需要改进

1 0
原创粉丝点击