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 {
public:
    string add(string num1, string num2){
        int i = 0, j = 0, c = 0,m = 0;
        string ans;
        while(i < num1.size() || j < num2.size()){
            if (i < num1.size() && j < num2.size()){
                m = c + (num1[i++] - '0') + (num2[j++] - '0');
            }else if (i < num1.size()){
                m = c + (num1[i++] - '0');
            }else{
                m = c + (num2[j++] - '0');
            }
            ans += (m%10 + '0');
            c = m/10;
        }
        if (c){
            ans += '1';
        }
        return ans;
    }
    string multiply(string num1, string num2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        string ans,temp,ans1;
        reverse(num1.begin(),num1.end());
        reverse(num2.begin(),num2.end());
        ans = '0';
        
        int c = 0, i = 0, j = 0, m;
            
        for(int i = 0; i < num1.size(); i++){
            temp.clear();
            c = 0;
            for(int k = 0; k < i; k++){
                temp += '0';
            }
            for(int j = 0; j < num2.size(); j++){
                m = (num1[i] - '0') * (num2[j] - '0');                 m += c;
                temp += (m%10 + '0');
                c = m/10;
            }
            if (c){
                temp += (c + '0');
            }
            ans = add(ans,temp);
        }
        reverse(ans.begin(),ans.end());
        //ans前面的0都去掉
        bool ok = false;
        for(int k = 0; k < ans.size(); k++){
            if (ans[k] != '0'){
                ok = true;
            }
            if (ok || ans[k] != '0'){
                ans1 += ans[k];
            }
        }
        if (!ans1.size()) ans1 = '0';
        return ans1;
    }
};

 

posted @ 2013-07-14 00:07  一只会思考的猪  阅读(202)  评论(0编辑  收藏  举报