当前位置:网站首页>【力扣】字符串相乘
【力扣】字符串相乘
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;
}
};边栏推荐
猜你喜欢

WeChat applet cloud development | personal blog applet

Day33 LeetCode

R语言 线性回归的有关方法

2022牛客多校联赛第五场 题解

进行交互或动画时如何选择Visibility, Display, and Opacity

Questions I don't know in database kernel interview(1)

ISC2022 HackingClub白帽峰会倒计时1天!最全议程正式公布!元宇宙集结,精彩绝伦!

移植MQTT源码到STM32F407开发板上

Excel advanced drawing techniques, 100 (22) - how to respectively the irregular data

CS-NP白蛋白包覆壳聚糖纳米颗粒/人血清白蛋白-磷酸钙纳米颗粒无机复合材料
随机推荐
徒步,治好了我的精神内耗
正则表达式
C专家编程 前言
Nacos 配置中心
C语言_联合体共用体引入
(七)《数电》——CMOS与TTL门电路
Pytorch框架学习记录8——最大池化的使用
win10版本1803无法升级1903系统如何解决
C Pitfalls and pitfalls Appendix B Interview with Koenig and Moo
函数(二)
Pytorch框架学校记录11——搭建小实战完整细节
Postman 批量测试接口详细教程
ISC2022 HackingClub白帽峰会倒计时1天!最全议程正式公布!元宇宙集结,精彩绝伦!
Pytorch学习记录(八):生成对抗网络GAN
WeChat applet cloud development | personal blog applet
LeetCode·32.最长有效括号·栈·动态规划
Taobao's API to get the list of shipping addresses
98. Embedded controller EC actual combat EC development board development completed
JS提升:手写发布订阅者模式(小白篇)
附录A printf、varargs与stdarg A.1 printf函数族