leetcode【第六周】字符串数字相乘

问题描述:

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.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

问题分析:

如题所述,需要将两个字符串的数字进行相乘,然后结果再用字符串输出。字符串乘法能突破数据类型计算两个长值的数字相乘的限制,具有实际意义。

实现思路可以按照手写乘法的方式来实现,即使用两个数字的各位数值进行逐位相乘,保存在一个结果数组中,再对数组中各数值进行进位处理。最后根据结果数组的值输出字符串即可。

代码如下:

class Solution {
public:
    string multiply(string num1, string num2) {
        
        
        
        int len1 = num1.length();
        int len2 = num2.length();
        reverse(num1.begin(),num1.end());
        reverse(num2.begin(),num2.end());
        int data[len1+len2]={0};
        for(int i=0;i0)
        {
            index--;
            if(!flag&&data[index]==0)continue;
            else
            {
                flag = true;
                result += (char)(data[index]+'0');
            }
            
        }
        if(!flag) return "0";
        return result;
    }
};

运行时间:

9ms

你可能感兴趣的:(leetcode【第六周】字符串数字相乘)