leetcode: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.

题意给两个字符串表示的数字,计算他们的乘积。

其实就是手写一个大数乘法,先翻转字符串便于从低位开始计算。

模拟乘法的运算过程,把中间结果存在data中,最后在考虑data的进位并存到结果字符串里。

注意点的就是考虑结果的前置0不要添加进去。


int data[100000];
class Solution {
public:
    string multiply(string num1,string num2) {
        reverse(num1.begin(),num1.end());
        reverse(num2.begin(),num2.end());
        memset(data,sizeof(data));
        int len1=num1.length();
        int len2=num2.length();
        int i,j;
        for(i=0;i<len1;++i)for(j=0;j<len2;++j)
        {
            data[j+i]+=(num1[i]-'0')*(num2[j]-'0');
        }
        int p,temp;
        i=p=0;
        while(i<len1+len2-1||p!=0)
        {
            temp=data[i]+p;
            data[i]=temp%10;
            p=temp/10;
            ++i;
        }
        string result;
        bool flag=0;
        for(;i>=0;--i)
        {
            if(flag==0&&data[i]==0)continue;
            else
            {
                flag=1;
                result+=(char)(data[i]+'0');
            }
        }
        if(flag==0)return "0";
        else return result;
    }
};

相关文章

自1998年我国取消了福利分房的政策后,房地产市场迅速开展蓬...
文章目录获取数据查看数据结构获取数据下载数据可以直接通过...
网上商城系统MySql数据库设计
26个来源的气象数据获取代码
在进入21世纪以来,中国电信业告别了20世纪最后阶段的高速发...