1. 程式人生 > >大數乘法 leetcode 43. Multiply Strings

大數乘法 leetcode 43. Multiply Strings

class Solution {
    public:
        string multiply(string num1, string num2) {
            int len1 = num1.length();
            int len2 = num2.length();
            string result(len1+len2, '0');
            int cal = 0,tmp = 0;
            if( num1=="0" || num2 =="0") return "0";
            for(int i =
len1 - 1; i >= 0; --i) { for(int j = len2 - 1; j >= 0; --j) { tmp = (result.at(i+j+1)-'0') + (num1.at(i) - '0') * (num2.at(j) - '0')+ cal; result.at(i+j+1) = ( tmp % 10) +'0'; cal = tmp / 10; if
(i ==0 && j ==0 && cal !=0) { result.at(0) = cal + '0'; cal = 0; } else if(j == 0 && cal !=0) { result.at(i) = cal +'0'; cal =
0; } } } if(result.at(0) == '0') { result.erase(0,1); } return result; } };