Saturday, September 20, 2014

LeetCode: 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.

   void reverse(string &s)  
   {  
     int i = 0, j = s.length()-1;  
     while(i<j)  
     {  
       swap(s[i],s[j]);  
       i++;  
       j--;  
     }  
   }  

   string add(string str1, string str2)  
   {  
     string s;  
     int n1 = str1.length(), n2 = str2.length();  
     int i =0, j =0, carry = 0;  
     while(i<n1 && j<n2)  
     {  
       int sum = (str1[i] - '0') + (str2[j] - '0') +carry;  
       s += sum%10 + '0';  
       carry = sum/10;  
       i++; j++;  
     }  
     while(i<n1)  
     {  
       int sum = (str1[i] - '0') +carry;  
       s += sum%10 + '0';  
       carry = sum/10;  
       i++;  
     }  
     while(j<n2)  
     {  
       int sum = (str2[j] - '0') +carry;  
       s += sum%10 + '0';  
       carry = sum/10;  
       j++;  
     }  
     if(carry)  
     {  
       s += carry + '0';  
     }  
     return s;  
   }  

   string multiply(string num1, string num2) {  
     string s, res="0";  
     int n1 = num1.length();  
     int n2 = num2.length();  
     int carry = 0;  
     reverse(num1);  
     reverse(num2);  
     for(int i = 0; i <n2; i++)  
     {  
       carry = 0;  
       s = "";  
       for (int k = 0; k<i; k++)s += '0';  
       for (int j = 0; j <n1; j++)  
       {  
         int m = (num2[i] - '0') * (num1[j] - '0') + carry;  
         s += m%10 + '0';  
         carry = m/10;  
       }  
       while(carry){  
         s += carry%10 + '0';  
         carry = carry/10;  
       }  
       res = add(res,s);  
     }  
     reverse(res);  
     int n = res.length()-1;  
     int i = 0;  
     while(i<n && res[i] == '0')i++;  
     res = res.substr(i);  
     return res;  
   }  

No comments:

Post a Comment