Multiply Strings ---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.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.

Subscribe to see which companies asked this question

这是来自于leetcode上的一道算法题目。

算法思路:用char存储大数的每一位,然后控制每一位之间的相乘和进位即可。

我的代码如下:

class Solution {
public:
    string multiply(string num1, string num2) {
	const char *ch1 = num1.c_str();
	const char *ch2 = num2.c_str();
	const unsigned int l1=num1.length();
	const unsigned int l2=num2.length();
	const unsigned int lc = l1 +l2 +1;
	//cout<<str1.length()+str2.length()+1<<endl;
	char *ch3 = (char *)malloc((lc+1)*sizeof(char));
	for (int i = 0; i < lc; i++)
	{
		ch3[i]='0';
	}
	for (int i = l1 - 1; i >= 0 ; i--)
	{
		unsigned int start = (l1-i);
		int re = 0;
		for (int j = l2 - 1; j >= 0 ; j--)
		{
			int temp = (ch1[i]-48)*(ch2[j]-48) + re;
			int result = ch3[lc - (l1-i)-(l2-j)]+(temp%10) -48;
			re =temp/10;
			if (result>9)
			{
				re+=result/10;
				result=result%10;
			}
			ch3[lc - (l1-i)-(l2-j)]= result+48;
			if (j==0)
			{
				ch3[lc - (l1-i)-(l2-j)-1]=re+48;
			}
		}
	}
	string a(ch3);
	free(ch3);
	int i=0;
	for(;i<lc-2;i++){
	    if(a.substr(i,1)=="0")continue;
	    else break;
	}
    return a.substr(i,lc-i-1);
    }
};
结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值