zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    C# UrlDecode将+替换为空格问题
    Hashtable无序,用Dictionary代替
    Oracle查找Web执行SQL
    远程连接Oracle服务器
    asp.net core网站SSL nginx配置
    Supervisor踩过的坑
    centos nginx配置支持WebSocket(signalR)
    SignalR在asp.net core下使用
    Hangfire 在asp.net core环境的使用
    liteUploader上传控件的封装使用
  • 原文地址:https://www.cnblogs.com/aiterator/p/6633162.html
Copyright © 2011-2022 走看看