Multiply Strings ---leetcode
2016-07-18 16:21
288 查看
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);
}
};结果:
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);
}
};结果:
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- C#算法函数:获取一个字符串中的最大长度的数字
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 经典排序算法之冒泡排序(Bubble sort)代码
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法