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

STAHL touch screen repair all-in-one display screen ET-316-TX-TFT common faults

Hiking, cured my mental internal friction

wps excel 插入公式 整列

关于Request复用的那点破事儿。研究明白了,给你汇报一下。

CS-NP白蛋白包覆壳聚糖纳米颗粒/人血清白蛋白-磷酸钙纳米颗粒无机复合材料

Internet使用的网络协议是什么

OSG Notes: Set DO_NOT_COMPUTE_NEAR_FAR to manually calculate far and near planes

Pytorch框架学习记录9——非线性激活

property语法

徒步,治好了我的精神内耗
随机推荐
职场如象棋,测试/开发程序员如何突破成长瓶颈期?
Get started with Grafana in 15 minutes
tiup mirror genkey
JSD - 2204 - Knife4j framework - processing - Day07 response results
列表页常见的 hook 封装
附录A printf、varargs与stdarg A.1 printf函数族
Transplant MQTT source code to STM32F407 development board
线上一次JVM FullGC搞得整晚都没睡,彻底崩溃~
C pitfalls and pitfalls Chapter 7. Portability pitfalls 7.10 Free first, then realloc
牛血清白蛋白刺槐豆胶壳聚糖缓释纳米微球/多西紫杉醇的纳米微球DTX-DHA-BSA-NPs
R语言 线性回归的有关方法
封装一个管理 url 状态的 hook
OSG Notes: Set DO_NOT_COMPUTE_NEAR_FAR to manually calculate far and near planes
Pytorch框架学习记录12——完整的模型训练套路
面试突击70:什么是粘包和半包?怎么解决?
有点奇怪!访问目的网址,主机能容器却不行
宝塔搭建PESCMS-Ticket开源客服工单系统源码实测
通过这两个 hook 回顾 Set/Map 基础知识
那些关于DOM的常见Hook封装(二)
软考 ----- UML设计与分析(上)