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

LeetCode--Multiply Strings

时间:2015-01-16 11:25:18      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:leetcode   string   multiply   

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 {
public:
    string multiply(string num1, string num2) 
    {
        if(num1=="0" || num2=="0")
            return "0";
        int n = num1.length();
        int m = num2.length();
        if(n<m)
            return multiply(num2,num1);
        string temp;
        string res = "";
        int i,j=m-1,count;
        int num0 = 0;
        while(j>=0)
        {
            temp = "";
            count = 0;
            i=n-1;
            while(i>=0)
            {
                count = count + (num1[i]-48)*(num2[j]-48);
                temp = temp + (char)(count%10+48);
                count = count/10;
                i--;
            }
            if(count!=0)
                temp = temp + (char)(count+48);
            int low = 0;
            int high = temp.length()-1;
            while(low<high)
                swap(temp,low++,high--);
            for(int i=0; i<num0; i++)
                temp= temp + "0";
            res = add(res,temp);
            num0++;
            j--;
        }
        return res;
    }
    void swap(string& s, int i, int j)
    {
        char t = s[i];
        s[i] = s[j];
        s[j] = t;
    }
    string add(string a, string b)
    {
        string res="";
        int n = a.length();
        int m = b.length();
        if(n==0)
            return b;
        if(m==0)
            return a;
        int i=n-1,j=m-1;
        int count = 0;
        while(i>=0 || j>=0)
        {
            if(i<0)
            {
                count = count + b[j]-48;
                res = res + (char)(count%10 + 48);
                count = count/10;
                j--;
            }
            else if(j<0)
            {
                count = count + a[i]-48;
                res = res + (char)(count%10 + 48);
                count = count/10;
                i--;
            }
            else
            {
                count = count + (a[i]-48)+(b[j]-48);
                res = res + (char)(count%10 + 48);
                count = count/10;
                j--;
                i--;
            }
        }
        if(count!=0)
            res = res + (char)(count+48);
        int low = 0;
        int high = res.length()-1;
        while(low<high)
            swap(res,low++,high--);
        return res;
    }
};


LeetCode--Multiply Strings

标签:leetcode   string   multiply   

原文地址:http://blog.csdn.net/shaya118/article/details/42773715

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