zoukankan      html  css  js  c++  java
  • 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.

    class Solution {
    private:
        void reverse(string& s)
        {
            int l=0;
            int r=s.length()-1;
            while(l<r)
            {
                char c=s[l];
                s[l]=s[r];
                s[r]=c;
                l++;
                r--;
            }
        }
        void add(string& s1,string s2)
        {        
            while(s1.length()<s2.length()) s1=s1+'0';
            while(s2.length()<s1.length()) s2=s2+'0';
            int add=0;
            for(int i=0;i<s1.length();i++)
            {
                int sum=add+s1[i]+s2[i]-'0'-'0';
                s1[i]=sum%10+'0';
                add=sum/10;
            }
            if(add>0) s1=s1+char(add+'0');
        }
        void mul(string& s,int n)
        {
            int add=0;
            for(int i=0;i<s.length();i++)
            {
                int sum=(s[i]-'0')*n+add;
                s[i]=sum%10+'0';
                add=sum/10;
            }
            if(add>0) s=s+char('0'+add);
        }
        void fix(string& s)
        {
            if(s.length()==0) s="0";        
            int index=s.length()-1;
            while(index>0 && s[index]=='0') index--;
            string result;
            for(int i=0;i<=index;i++)
                result=result+s[i];
            s=result;
        }
    public:
        string multiply(string num1, string num2) 
        {
            reverse(num1);
            reverse(num2);

            string result;
            string tens;
            for(int i=0;i<num2.length();i++)
            {
                string num=num1;
                mul(num,num2[i]-'0');
                num=tens+num;
                add(result,num);

                tens=tens+'0';
            }
            
            fix(result);reverse(result);
           return result;
        }
    }; 
  • 相关阅读:
    mysql数据库操作
    django
    django-rest framwork
    Maven项目POM文件错误,提示“Plugin execution not covered by lifecycle configuration”的解决方案
    [Flutter] FFI之生成Ansi字符串指针
    多label实现准确率和召回率
    pickle.dump()和pickle.load()
    numpy.take()
    通俗易懂的lambda表达式,不懂来找我!
    collections(python常用内建模块)
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759357.html
Copyright © 2011-2022 走看看