当前位置:网站首页>【力扣】字符串相乘
【力扣】字符串相乘
2022-08-01 21:08:00 【Patrick star`】
题目:
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
思路:

m位数*n位数的结果一定小于等于m+n位数
代码:
class Solution {
public:
string multiply(string num1, string num2)
{
if (num1 =="0" ||num2=="0")
{
return "0";
}
int end1 = num1.size() - 1;
int end2 = num2.size() - 1;
int indexLen = end1 + end2 + 2;
int* index = new int[indexLen];
int end = indexLen-1;
int cur = end;
for (int i = 0; i <indexLen; i++)
{
index[i] = -1;
}
while (end2 >= 0)
{
cur = end;
while (end1 >= 0)
{
int temp = (num2[end2] - '0') * (num1[end1] - '0');
if (index[cur] == -1)
{
index[cur] = temp;
}
else
{
index[cur] += temp;
}
if (index[cur] > 9)
{
int carry = index[cur] / 10;
index[cur] = index[cur]%10;
if (index[cur-1] == -1)
{
index[cur - 1] = carry;
}
else
{
index[cur - 1] += carry;
}
}
cur--;
end1--;
}
end1 = num1.size() - 1;
end2--;
end--;
}
string ret;
for (int i = 0; i < indexLen; i++)
{
if (index[i]!=-1)
{
ret += index[i] + '0';
}
}
delete[] index;
return ret;
}
};边栏推荐
- C陷阱与缺陷 第7章 可移植性缺陷 7.11 可移植性问题的一个例子
- 包含吲哚菁绿的多聚体白蛋白纳米球/载马钱子碱纳米粒的牛血清白蛋白微球的制备
- 2022牛客多校联赛第五场 题解
- Internet使用的网络协议是什么
- 对C语言结构体内存对齐的理解
- 如何封装 cookie/localStorage/sessionStorage hook?
- [Chinese tree tags - CTB]
- MySQL 中出现的字符编码错误 Incorrect string value: ‘\x\x\x\x‘ for column ‘x‘
- [译] 容器和 Kubernetes 中的退出码完整指南
- Postman 批量测试接口详细教程
猜你喜欢
随机推荐
织梦发布文章提示body has not allow words错误
JS Improvement: Handwritten Publish Subscriber Model (Xiaobai)
Hiking, cured my mental internal friction
C陷阱与缺陷 第8章 建议与答案 8.2 答案
Questions I don't know in database kernel interview(1)
在Cesium中实现与CAD的DWG图叠加显示分析
使用员工管理软件,解锁人力生产力新水平,提高人力资源团队灵活性
附录A printf、varargs与stdarg A.3 stdarg.h ANSI版的varargs.h
Imitation cattle forum project
Review Set/Map basics with these two hooks
C陷阱与缺陷 第8章 建议与答案 8.1 建议
360借条安全专家:陌生微信好友不要轻易加贷款推广多是诈骗
C陷阱与缺陷 附录B Koenig和Moo夫妇访谈
kubernetes各名词缩写
C Pitfalls and Defects Chapter 7 Portability Defects 7.9 Case Conversion
string
JS提升:如何中断Promise的链式调用
【接口测试】JMeter调用JS文件实现RSA加密
Excel advanced drawing techniques, 100 (22) - how to respectively the irregular data
15 分钟带你入门 Grafana









