zoukankan      html  css  js  c++  java
  • 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,0,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;
        }
    };


  • 相关阅读:
    Python是如何进行内存管理的?
    scrapy利用set()对数据进行去重
    python快速抓取新闻标题及内容
    python爬虫第三方库
    Spring使用@Scheduled定时调度
    redis启动失败
    视图系统
    路由系统
    Django框架 part 2
    Django框架
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3343504.html
Copyright © 2011-2022 走看看