兩個數字字串相乘

來源:互聯網
上載者:User

求兩個字串的乘積,結果存到字串中,例如字串一中存的“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';}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.