43. Multiply Strings

Posted 小河沟大河沟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了43. Multiply Strings相关的知识,希望对你有一定的参考价值。

43. Multiply Strings

题目

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

Note:

    The length of both num1 and num2 is < 110.
    Both num1 and num2 contains only digits 0-9.
    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.

解析

  • 大数相乘原则
  • 认清楚乘法从后面开始乘,vec[size-1]是最小位
// add 43. Multiply Strings
class Solution_43 {
public:
    string multiply(string num1, string num2) {
        int len1 = num1.size();
        int len2 = num2.size();

        vector<int> vec(len1+len2,0); // 初始化内存空间
        //vec.reserve(len1 + len2);
        
        for (int i = 0; i < len1; i++)
        {
            int k = i;
            for (int j = 0; j < len2;j++)
            {
                //vec.push_back(a*b);
                vec[k] += (num1[len1-1-i] - '0')*(num2[len2-1-j]-'0');  ////Calculate from rightmost to left
                k++; 
            }
        }

        string ret="";
        for (int i = 0; i < vec.size();i++)
        {
            if (vec[i]>=10)
            {
                vec[i+1] += vec[i] / 10;
                vec[i] = vec[i] % 10;
            }
            //char temp[5];
            //_itoa(vec[i], temp, 10);
            //ret += temp;

            char temp = vec[i] + '0'; 
            ret += temp; //反着取得
        }

        //reserve(ret.begin(),ret.end());
        //reverse(vec.begin(), vec.end()); //string没有反转函数,vector有
        
        //判断第一个非0位 //size_t startpos = sum.find_first_not_of("0");
        int flag = 0;
        for (int i = ret.size()-1; i >=0;i--)
        {
            if (ret[i]!='0')
            {
                flag = i;
                break;
            }
        }

        int begin = 0, end = flag;
        while (begin < end)
        {
            swap(ret[begin], ret[end]);
            begin++;
            end--;
        }

        return ret.substr(0,flag+1);
    }
};

题目来源

以上是关于43. Multiply Strings的主要内容,如果未能解决你的问题,请参考以下文章

43. Multiply Strings

#Leetcode# 43. Multiply Strings

Leetcode 43. Multiply Strings

43. Multiply Strings

43. Multiply Strings

LeetCode 43. Multiply Strings