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

leetcode - Multiply Strings

时间:2014-10-25 09:21:02      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   ar   for   on   bs   line   size   

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:
    std::string multiply(std::string num1, std::string num2) {
		if(num1 == "0" || num2 == "0") return "0";
		int l1 = num1.size(),l2 = num2.size();
		std::vector<int> vec1(l1,0);
		std::vector<int> vec2(l2,0);
		std::vector<int> res(l1+l2,0);
		for (int i = 0; i < l1; i++)
		{
			vec1[i] = num1[i] - '0';
		}
		for (int i = 0; i < l2; i++)
		{
			vec2[i] = num2[i] - '0';
		}
		for (int i = 0; i < l1; i++)
		{
			for (int j = 0; j < l2; j++)
			{
				res[i+j+1] += vec1[i] * vec2[j];
			}
		}
		std::string s;
		for(int i = l1 + l2 - 1; i >= 0; i--)
		{
			if(res[i] > 0) res[i-1] += res[i] / 10;
			res[i] %= 10;
			s = (char)(res[i] + '0') + s;
		}
		return s[0] == '0' ? s.substr(1) : s;
    }
};


leetcode - Multiply Strings

标签:style   color   io   ar   for   on   bs   line   size   

原文地址:http://blog.csdn.net/akibatakuya/article/details/40436927

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