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

Leetcode Multiply Strings

时间:2014-07-07 14:58:47      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   io   leetcode   

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

 

Leetcode Multiply Strings,布布扣,bubuko.com

Leetcode Multiply Strings

标签:style   blog   color   for   io   leetcode   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3815224.html

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