两个数字字符串相乘

来源:互联网 发布:电动插桶泵淘宝 编辑:程序博客网 时间:2024/05/17 23:58

求两个字符串的乘积,结果存到字符串中,例如字符串一中存的“657891”,字符串二中存的“521”

输出342761211

#include<stdio.h>#include<malloc.h>#include<string.h>#include<assert.h>void mul(char *Input1, int n, char *Input2, int m,char *Output);int main(){int n, m;int i = 0;char Input1[100];char Input2[100];char *Output;char *Result;gets(Input1);gets(Input2);n = strlen(Input1);m = strlen(Input2);Output = (char *)malloc(sizeof(char) * (m+n+1));assert(n>0 && m > 0 && Output != NULL);mul(Input1, n, Input2, m,Output);Result = Output;while(*Result == '0' && Result < Output+(m+n-1))//如果结果是0,输出一个0Result++;printf("%s\n", Result);        free(Output);        return 0;}void mul(char *Input1, int n, char *Input2, int m,char *Output){int i = 0;int j = 0;char *endIn1 = Input1+n-1;char *endIn2 = Input2 + m-1;char *endOut = Output + m+n-1;char *ptemp;int overflow = 0;for(i = 0; i < n+m; ++i)Output[i] = '0';Output[i] = '\0';while(endIn2 >= Input2) //从乘数的最后一位开始依次与乘数相乘{ptemp = endOut;  while(endIn1 >= Input1)  {i = *endIn2 - '0';j = *endIn1 - '0';*ptemp += (i*j % 10 + overflow); //output原来的值 + 进位 + 这次乘的结果(可能大于10)overflow = i*j/10 + (*ptemp - '0')/10;//进位的值*ptemp = (*ptemp-'0')%10 + '0';  //output 的真实值ptemp--;  //依次计算output的每一位的值endIn1--; }if(overflow != 0) //最后是不是还有进位*ptemp = overflow + '0';overflow = 0;endIn1 = Input1+n-1;endOut--;//每一轮循环相乘之后,与Output的最低位相加的时候也要左移一位endIn2--;}Output[m+n] = '\0';}



原创粉丝点击