CUIT 2016 新生訓練題第一週 C - Bull Math

C - Bull Math

 
Bulls are so much better at math than the cows. They can multiply huge integers together and get perfectly precise answers ... or so they say. Farmer John wonders if their answers are correct. Help him check the bulls' answers. Read in two positive integers (no more than 40 digits each) and compute their product. Output it as a normal number (with no extra leading zeros). 

FJ asks that you do this yourself; don't use a special library function for the multiplication.
Input
* Lines 1..2: Each line contains a single decimal number.
Output
* Line 1: The exact product of the two input lines
Sample Input
11111111111111
1111111111
Sample Output
12345679011110987654321


題解:最簡單的高精度乘法模板題目。
#include<stdio.h>
#include<string.h>
using namespace std;

char str1[45],str2[45];
int num1[45],num2[45];
int res[100];

int main()
{
    while(~scanf("%s%s",str1,str2))
    {
        /*重置部分*/
        memset(res,0,sizeof(res));
        memset(num1,0,sizeof(num1));
        memset(num2,0,sizeof(num2));

        /*讀入與轉化部分*/
        int len1=strlen(str1);
        int len2=strlen(str2);
        for(int i=len1-1; i>=0; i--) num1[len1-1-i]=str1[i]-'0';
        for(int j=len2-1; j>=0; j--) num2[len2-1-j]=str2[j]-'0';

        /*乘法運算部分*/
        for(int i=0; i<len1; i++)
        {
            for(int j=0; j<len2; j++)
            {
                res[i+j]+=num1[i]*num2[j];
            }
        }

	/*進位部分*/
        int length=len1+len2-1;
        for(int i=0;i<length;i++)
        {
            if(res[i]>9)
            {
                res[i+1]+=res[i]/10;
                res[i]%=10;
                if(i+1==length)
                {
                    length++;
                }
            }
        }

s	/*輸出部分*/
        for(int i=length-1; i>=0; i--)
        {
            printf("%d",res[i]);
        }
        printf("\n");
    }
}




發佈了36 篇原創文章 · 獲贊 14 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章