当前位置:编程学习 > C/C++ >>

poj_2389_Bull Math_解题报告

题目出处
-------------------------------------------------------------------------------------------题目-------------------------------------------------------------------------------------------
Bull Math
Time Limit: 1000MS
Memory Limit: 65536K
Total Submissions: 10910
Accepted: 5644
Description

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
-------------------------------------------------------------------------------------------结束-------------------------------------------------------------------------------------------
解法:简单模拟
要点:
数据的存储使用数组
观察乘法的规律,就可以先相乘再相加进位
注意:存储空间必须开大一点,不然就像我开始一样不断地WA,坑爹啊!
代码:(先相乘完再进位)
也可以把进位的代码放进每个数相乘的循环里
[cpp]
#include <iostream> 
using namespace std; 
 
const int MAX=40; 
const int result=80; 
 //空间必须开一些 
char    a[MAX+10];   //接受键盘输入的数 
char    b[MAX+10]; 
int     amul[MAX+10];//存储转换后的数 
int     bmul[MAX+10]; 
int     product[result+10];//存储乘积 
 
void interger(char *source, int *target, int length) 

    int    i = length-1; 
    int    index = 0; 
    for (; index < length; index++, i--) 
    { 
        //将数字字符转换为整数,下标0、1、2分别为个、十、百位 
        target[index] = source[i] - '0'; 
    } 

int main() 

    int    i, j; 
    cin >> a >> b; 
    if (!strcmp(a, "0") || !strcmp(a, "0")) 
    { 
        cout << "0" << endl; 
        return    0; 
    } 
    //将char转换为int 
    interger(a, amul, strlen(a)); 
    interger(b, bmul, strlen(b)); 
    //相乘不进位 
    for (i = 0; i < strlen(b); i++) 
    { 
        for (j = 0; j < strlen(a); j++) 
        { 
            //叠加到原来的位置的数上面 
            product[i+j] += bmul[i] * amul[j]; 
        } 
    } 
    //进位 
    for (i = 0; i < result; i++) 
    { 
        if (product[i] >= 10) 
        { 
            product[i + 1] += product[i] / 10; 
            product[i] = product[i] % 10;; 
        } 
    } 
    //把前导零去掉 
    int    k = result-1; 
    while (product[k] == 0) 
    { 
        k--; 
    } 
    //倒序输出 
    for (; k >= 0; k--) 
    { 
        cout << product[k]; 
    } 
    cout << endl; 
    return   0; 

(后续会尝试优化或增加不同的解法)

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,