Leetcode Multiply Strings

OpenSoucre發表於2014-06-29

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) {
        reverse(num1.begin(),num1.end());
        reverse(num2.begin(),num2.end());
        if(num1.length() < num2.length()) swap(num1,num2);
        string sum(num1.length()+num1.length()+1,'0');
        for(int i = 0 ;i < num2.length(); ++ i){
            int carry = 0;
            for(int j = 0 ; j < num1.length(); ++ j){
                int tmp = (num1[j]-'0')*(num2[i]-'0')+carry;
                carry = tmp/10;
                tmp = tmp%10+(sum[i+j]-'0');
                sum[i+j] ='0'+tmp%10;
                sum[i+j+1] = '0'+(sum[i+j+1]-'0' + tmp/10);
            }
            if(carry != 0){
                int num = carry+(sum[i+num1.length()]-'0');
                sum[i+num1.length()] = '0'+num%10;
                if(num/10) sum[i+num1.length()+1] = '0'+(sum[i+num1.length()+1]-'0'+num/10);
            }
        }
        reverse(sum.begin(),sum.end());
        int index = 0;
        for(index = 0 ; index < sum.length(); ++ index){
            if(sum[index]!='0') return string(sum.begin()+index, sum.end());
        }
        if(index == sum.length()) return "0";
    }
};

 

相關文章