• LeetCode 43. Multiply Strings


    Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

    Note:

    • 1.The length of both num1 and num2 is < 110.
    • 2.Both num1 and num2 contains only digits 0-9.
    • 3.Both num1 and num2 does not contain any leading zero.

    You must not use any built-in BigInteger library or convert the inputs to integer directly.

    典型的大整数乘法模拟

    class Solution {
    
        void CharToInt(string &str, vector<short int> &arr)
        {
            for(int i=str.size()-1; i>=0; -- i)
                arr.push_back(str[i]-'0');
        }
    
        void sum(vector<short int> &res, vector<short int> &ans)
        {
            int add = 0;
            for(int i=0; i<res.size(); ++ i)
            {
                ans[i] = res[i] + ans[i] + add;
                add = ans[i] / 10;
                ans[i] %= 10;
            }
            int i = res.size();
            while(add != 0)
            {
                ans[i] = ans[i] + add;
                add = ans[i] / 10;
                ans[i] %= 10;
            }
        }
    
    public:
        string multiply(string num1, string num2) {
            vector<short int> a, b;
            CharToInt(num1, a);
            CharToInt(num2, b);
    
            vector<short int> ans(12500, 0);
            for(int i=0; i<a.size(); ++ i)
            {
                vector<short int> res;
                for(int j=0; j<i; ++ j)
                    res.push_back(0);
                int add = 0;
                for(int j=0; j<b.size(); ++ j)
                {
                    int t = a[i] * b[j] + add;
                    res.push_back(t % 10);
                    add = t / 10;
                }
                if(add != 0)
                    res.push_back(add);
    
                sum(res, ans);
            }
    
            string str;
            bool is = false;
            for(int i=12499; i>=0; -- i)
            {
                if(ans[i] != 0)
                    is = true;
    
                if(is)
                    str += ans[i] + '0';
            }
            if(is == false)
                return "0";
            return str;
        }
    };
    
  • 相关阅读:
    【洛谷P6835】线形生物
    【洛谷P2679】子串
    【洛谷P5072】盼君勿忘
    【洛谷P3312】数表
    【洛谷P1447】能量采集
    【洛谷P2257】YY的GCD
    【洛谷P4318】完全平方数
    【AT2300】Snuke Line
    window.showModalDialog
    js typeof
  • 原文地址:https://www.cnblogs.com/aiterator/p/6633162.html
Copyright © 2020-2023  润新知