zoukankan      html  css  js  c++  java
  • [LeetCode] #43 Multiply Strings

    Given two numbers represented as strings, return multiplication of the numbers as a string.

    Note: The numbers can be arbitrarily large and are non-negative.

    本题先用数组存放每一位相乘后的累加数字,比如几个十,然后把它转换为string类型的数字,再去掉前面多余的0.时间:9ms。代码如下:

    class Solution {
    public:
        string multiply(string num1, string num2) {
            if (num1.size() == 0)
                return num2;
            else if (num2.size() == 0)
                return num1;
            vector<int> v(num1.size() + num2.size() - 1, 0);
            reverse(num1.begin(), num1.end());
            reverse(num2.begin(), num2.end());
            for (string::size_type i = 0; i < num2.size(); i++){
                if (num2[i] != '0'){
                    for (string::size_type j = 0; j < num1.size(); j++){
                        v[i + j] += (num1[j] - '0')*(num2[i] - '0');
                    }
                }
            }
            string str="";
            int temp(0);
            for (vector<int>::size_type i = 0; i < v.size(); i++){
                str += '0' + (v[i] + temp) % 10;
                temp = (v[i] + temp) / 10;
            }
            if (temp>0)
                str += '0' +  temp % 10;
            reverse(str.begin(), str.end());
            string::const_iterator iter = str.begin();
            for (; iter != str.end() && *iter == '0'; ++iter);
            if (iter == str.end())
                return "0";
            else
                return str.substr(iter - str.begin(), str.end() - iter);
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    带编译器的codeblocks下载地址
    联想拯救者s15k重装w10系统教程
    w10下Oracle 11g完全干净卸载
    小机房的树(codevs 2370)
    NOIP[2015] 运输计划(codevs 4632)
    ⑨要写信(codevs 1697)
    酒厂选址(codevs 1507)
    美丽的大树(codevs 2124)
    乘法运算(codevs 3254)
    货车运输(codevs 3287)
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4583765.html
Copyright © 2011-2022 走看看