加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

leetcode:Multiply Strings(字符串的乘法)【面试算法题】

发布时间:2020-12-14 03:59:08 所属栏目:大数据 来源:网络整理
导读:题目: 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. 题意给两个字符串表示的数字,计算他们的乘积。 其实就是手写一个大数乘法,先翻

题目:

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;
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读