[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.

class Solution {
public:
    string multiply(string num1, string num2) {
          string result;
          int len1 = num1.size(),len2 = num2.size();
          int flag = 0, n=0,num=0;
          if(num1=="0" || num2=="0")
             return "0";
          for(int i=len2-1;i>=0;i--){//for(1)       num2  乘数
              int len = result.size();
              int k = len-(len2-i);
              for(int j= len1-1;j>=0;j--){//for(2)  num1  被乘数
                  if(i==len2-1){
                      n = (num1[j]-'0')*(num2[i]-'0')+flag;
                      flag = (n-n%10)/10;
                      num  =  n-flag*10;
                      result.insert(result.begin(),num+'0');
                      if(j==0 && flag!=0){
                          result.insert(result.begin(),flag+'0');
                          flag = 0;
                      }         
                  }else{ 
                      if(k>=0){
                          n = (num1[j]-'0')*(num2[i]-'0')+flag+(result[k]-'0');
                          flag = (n-n%10)/10;
                          num  =  n-flag*10;
                          result[k] =  num+'0';
                          if(j==0 && flag!=0){
                              result.insert(result.begin(),flag+'0');
                              flag = 0;
                          } 
                      }else if(k<0){
                          n = (num1[j]-'0')*(num2[i]-'0')+flag;
                          flag = (n-n%10)/10;
                          num  =  n-flag*10;
                         result.insert(result.begin(),num +'0');
                         if(j==0 && flag!=0){
                              result.insert(result.begin(),flag+'0');
                              flag = 0;
                          }
                      }
                          
                      k--;
                  }
              }//end for(2)
          }//end for(1)
        
          return result;
    }//end func
};

 

posted @ 2014-08-20 10:35  Xylophone  Views(104)  Comments(0Edit  收藏  举报