題目鏈接:
使用兩個char字符串來保存輸入,然後進行對字符串進行反轉,操作的時候就會方便一些。直接把計算的結果保存得另外一個int型數組中。具體看代碼:
#include<iostream> #include<cstdio> #include<cstring> #include<string.h> using namespace std; char number1[255]; char number2[255]; int answer[515]; void reverseNumber(char*); int main() { while(gets(number1)!=NULL&&gets(number2) != NULL) { memset(answer,0,sizeof(answer)); reverseNumber(number1); reverseNumber(number2); int length1=strlen(number1); int length2=strlen(number2); int answerLength=length1+length2; int i,j,carryBit=0; for(i=0;i<length1;i++) { for(j=0;j<length2;j++) { carryBit=answer[i+j]+(number1[i]-'0')*(number2[j]-'0'); answer[i+j]=carryBit%10; answer[i+j+1]+=carryBit/10; } } int flag=1; for(int index=answerLength;index>=1;index--) if(flag) { if(answer[index]) { cout<<answer[index]; flag=0; } } else cout<<answer[index]; cout<<answer[0]<<endl; } return 0; } /** reverse the string **/ void reverseNumber(char* number) { int length=strlen(number); for(int i=0,j=length-1;i<j;i++,j--) { char temp=number[i]; number[i]=number[j]; number[j]=temp; } } #include<iostream> #include<cstdio> #include<cstring> #include<string.h> using namespace std; char number1[255]; char number2[255]; int answer[515]; void reverseNumber(char*); int main() { while(gets(number1)!=NULL&&gets(number2) != NULL) { memset(answer,0,sizeof(answer)); reverseNumber(number1); reverseNumber(number2); int length1=strlen(number1); int length2=strlen(number2); int answerLength=length1+length2; int i,j,carryBit=0; for(i=0;i<length1;i++) { for(j=0;j<length2;j++) { carryBit=answer[i+j]+(number1[i]-'0')*(number2[j]-'0'); answer[i+j]=carryBit%10; answer[i+j+1]+=carryBit/10; } } int flag=1; for(int index=answerLength;index>=1;index--) if(flag) { if(answer[index]) { cout<<answer[index]; flag=0; } } else cout<<answer[index]; cout<<answer[0]<<endl; } return 0; } /** reverse the string **/ void reverseNumber(char* number) { int length=strlen(number); for(int i=0,j=length-1;i<j;i++,j--) { char temp=number[i]; number[i]=number[j]; number[j]=temp; } }