美文网首页
uva10106 Product

uva10106 Product

作者: 科学旅行者 | 来源:发表于2016-11-04 18:39 被阅读67次

    题目:

    The problem is to multiply two integers X, Y . (0 ≤ X, Y < 10250)
    Input
    The input will consist of a set of pairs of lines. Each line in pair contains one multiplyer.
    Output
    For each input pair of lines the output line should consist one integer the product.
    Sample Input
    12
    12
    2
    222222222222222222222222
    Sample Output
    144
    444444444444444444444444

    其实这道题就是大数乘法,不过要注意前导零,另外结果为0的情况要特判。

    参考代码:

    #include <iostream>
    #include <algorithm>
    #include <string>
    using namespace std;//两位数和两位数相乘最多不超过4位数;
    
    void bigmultiply(string a, string b) {
        int lena = a.size();
        int lenb = b.size();
        int lenr = lena + lenb;
        int *a1 = new int[lena];
        int *b1 = new int[lenb];
        int *result1 = new int[lenr];
    
        for (int i = 0;i < lenr;++i) {//这里要小心乱码,最好进行初始化;
            result1[i] = 0; 
        }
    
        int x, y, z;//记录个位十位;//10以内的两个数相乘结果均为2位数;
        int curr;//记录当前正在计算的位置, 倒序;
        
        for (int i = 0;i < a.size();++i) a1[i] = a[i] - '0';//将字符转换为数字;
        for (int i = 0;i < b.size();++i) b1[i] = b[i] - '0';
        /*  
        for (int i = 0;i < lena;++i) {
            cout << a1[i];
        }
        cout << endl;
        for (int j = 0;j < lenb;++j) {
            cout << b1[j];
        }   
        cout << endl;
        */
        for (int i = b.size()-1;i >= 0;--i) {
            curr = a.size() + i;//实际为lenr - (lenb - i)得到; 
            for (int j = a.size()-1;j >= 0;--j) {
                z = b1[i] * a1[j] + result1[curr];//上一位传过来的进位;
                //cout << "................" << z << endl;
                x = z % 10;//提取个位;
                y = z / 10;//提取十位;
                result1[curr] = x;
                curr--;
                result1[curr] += y;//相当于进位; 
            }
        }
        int pos = 0;
        for (int i = 0;i < lenr;++i) {
            if (result1[i] != 0) {
                pos = i;
                break;
            }
        }
        //cout << lenr << " " << pos << endl;   
        for (int i = pos;i < lenr;++i) {
            //cout << result1[i] << endl;
            cout << result1[i];
        }
        cout << endl;
        delete[] a1;
        delete[] b1;
        delete[] result1;
    }
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(NULL);
        string a, b;
        while (cin >> a >> b) {
            //cout << a << " " << b << endl;
            if (a == "0" || b == "0") cout << "0" << endl;
            else bigmultiply(a, b);
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:uva10106 Product

          本文链接:https://www.haomeiwen.com/subject/spjwuttx.html