当前位置:网站首页>【力扣】字符串相乘
【力扣】字符串相乘
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;
}
};
边栏推荐
猜你喜欢
随机推荐
Classification interface, Taobao classification details API
这些 hook 更优雅的管理你的状态
C语言_联合体共用体引入
牛血清白蛋白刺槐豆胶壳聚糖缓释纳米微球/多西紫杉醇的纳米微球DTX-DHA-BSA-NPs
职场如象棋,测试/开发程序员如何突破成长瓶颈期?
Godaddy domain name resolution is slow and how to use DNSPod resolution to solve it
Go Atomic
在Cesium中实现与CAD的DWG图叠加显示分析
JS hoisting: how to break the chain of Promise calls
[译] 容器和 Kubernetes 中的退出码完整指南
Based on FPGA in any number of bytes (single-byte or multibyte) serial port (UART) to send (including source engineering)
移植MQTT源码到STM32F407开发板上
C陷阱与缺陷 第7章 可移植性缺陷 7.7 除法运算时发生的截断
PyTorch笔记 - Attention Is All You Need (2)
响应式织梦模板清洁服务类网站
tiup mirror grant
【Kaggle】Classify Leaves
ISC2022 HackingClub白帽峰会倒计时1天!最全议程正式公布!元宇宙集结,精彩绝伦!
【中文树库标记---CTB】
仿牛客论坛项目