码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Multiply Strings

时间:2014-08-20 11:57:22      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   div   amp   

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
};

 

[LeetCode] Multiply Strings,布布扣,bubuko.com

[LeetCode] Multiply Strings

标签:style   blog   color   io   for   ar   div   amp   

原文地址:http://www.cnblogs.com/Xylophone/p/3924001.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!