码迷,mamicode.com
首页 > 其他好文 > 详细

Multiply Strings

时间:2014-06-04 20:19:04      阅读:313      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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.

bubuko.com,布布扣
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;
    }
}; 
bubuko.com,布布扣

Multiply Strings,布布扣,bubuko.com

Multiply Strings

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/erictanghu/p/3759357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!