当前位置:网站首页>LeetCode_43_字符串相乘
LeetCode_43_字符串相乘
2022-08-09 02:47:00 【Fitz1318】
题目链接
题目描述
给定两个以字符串形式表示的非负整数 num1
和 num2
,返回 num1
和 num2
的乘积,它们的乘积也表示为字符串形式。
注意:不能使用任何内置的 BigInteger
库或直接将输入转换为整数。
示例 1:
输入: num1 = "2", num2 = "3"
输出: "6"
示例 2:
输入: num1 = "123", num2 = "456"
输出: "56088"
提示:
1 <= num1.length, num2.length <= 200
num1
和num2
只能由数字组成。num1
和num2
都不包含任何前导零,除了数字0本身。
解题思路
竖式运算思想,以123 * 456为例子
遍历num2
每一位与num1
相乘,并将每一步的结果进行累加
AC代码
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
String ans = "0";
for (int i = num2.length() - 1; i >= 0; i--) {
int jinwei = 0;
StringBuilder tmp = new StringBuilder();
//补0
for (int j = 0; j < num2.length() - 1 - i; j++) {
tmp.append(0);
}
int n2 = num2.charAt(i) - '0';
//num2的第i位数字n2与num1相乘
for (int j = num1.length() - 1; j >= 0 || jinwei != 0; j--) {
int n1 = j >= 0 ? num1.charAt(j) - '0' : 0;
int product = n1 * n2 + jinwei;
tmp.append(product % 10);
jinwei = product / 10;
}
ans = addStrings(ans, tmp.reverse().toString());
}
return ans;
}
private static String addStrings(String num1, String num2) {
StringBuilder ans = new StringBuilder();
int jinwei = 0;
for (int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; i--, j--) {
int x = (i >= 0 ? num1.charAt(i) - '0' : 0);
int y = (j >= 0 ? num2.charAt(j) - '0' : 0);
int sum = x + y + jinwei;
ans.append(sum % 10);
jinwei = sum / 10;
}
ans.append(jinwei == 1 ? jinwei : "");
return ans.reverse().toString();
}
}
边栏推荐
- grafana的panel点击title,没有反应,没有出现edit选项
- [Redis] The core principle of master-slave replication
- 全志平台双路LVDS配置
- Postman接口测试【官网】最新版本 安装及使用入门教程
- 第二部分:和查找表相关的问题
- uart_spi练习
- 2022年自然语言处理校招社招实习必备知识点盘点分享
- 【物理应用】基于El-centro地震波作用下隔震与非隔震支座下的顶层位移、速度、加速度的对比情况附matlab代码
- Pytest+request+Allure实现接口自动化框架
- Recently, I have seen a lot of people who want to study by themselves or enroll in classes but don’t know how to choose. I will tell you about it today.
猜你喜欢
数字 01 Vivado2018.2安装及实操
独立机器连接cdh的spark集群,远程提交任务(绝对可以成功,亲测了n遍)
[TensorRT] 对UNet进行推理加速
OpenLORIS-Object Datasets
非关系型数据库MongoDB:(二)副本集部署说明、数据迁移、限制内存、启用mongo认证
What aspects should we start with for interface security testing?
最近看到很多人想自学或者报班但是不清楚如何选择,我今天就和大家说说
全志平台双路LVDS配置
A40i gxl3680 ts_print报错:tslib: Selected device is not a touchscreen (must support ABS and KEY event
【剑指offer65】不适用加减乘除做加法
随机推荐
Postman interface test [official website] latest version installation and use tutorial
Appium常用操作及H5页面元素定位
Open3D 计算点云的均值(质心)与协方差
目标检测中mAP计算以及源码解析
Rotate the neon circle
online schema change and create index
如何实现有状态转化操作
1160. 拼写单词
不会吧!不会吧!居然还有人不知道重绘以及回流
jmeter的websocket插件安装和使用方法
【洛谷】P5091 【模板】扩展欧拉定理
[TensorRT] 对UNet进行推理加速
第一部分:和数组相关的问题
Jenkins environment deployment, (packaging, publishing, deployment, automated testing)
Jenkins configuration nail notification
连接数据库且在网页运行的RDLC
Doris从理论详解到千万级数据量场景使用
普通人如何增加收入
【图像去噪】基于边缘增强扩散 (cEED) 和 Coherence Enhancing Diffusion (cCED) 滤波器实现图像去噪附matlab代码
书签收藏难整理?这款书签工具管理超方便