当前位置:网站首页>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();
}
}
边栏推荐
- Linux安装Redis
- 数字 07 verilog仿真实例
- 【洛谷】P5091 【模板】扩展欧拉定理
- 书签收藏难整理?这款书签工具管理超方便
- 第一部分:和数组相关的问题
- Open3D 随机采样
- 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.
- Likou Brush Question Record 4.1-----209. The sub-array with the smallest length
- 20220525动态规划:跳跃游戏
- SwiftUI * Grid
猜你喜欢
带你做接口测试从零到第一条用例 总结
二分搜索法和二叉搜索树
原文翻译:Structure Aware Single-stage 3D Object Detection from Point Cloud
MES对接Simba实现展讯平台 IMEI 写号与耦合测试
最新工业界推荐系统数据集-召回排序模型原理、结构及代码实战整理分享
书签收藏难整理?这款书签工具管理超方便
时间复杂度和空间复杂度
Likou Brush Question Record 4.1-----209. The sub-array with the smallest length
Programmer's Daily Life | Daily Fun
【信号去噪】基于Sage-Husa自适应卡尔曼滤波器实现海浪磁场噪声抑制及海浪磁场噪声的产生附matlab代码
随机推荐
如何实现有状态转化操作
20220527动态规划:零钱兑换
【Redis】主从复制的核心原理
7月更新速递 | 产品实验室N+1,EasyV For Unreal上线!
Qt 信号槽connect的同步与异步处理
书签收藏难整理?这款书签工具管理超方便
OpenLORIS-Object Datasets
Rotate the neon circle
概率模型校准
最强分布式锁工具:Redisson
20220529设计问题:二叉树的序列化与反序列化
online schema change and create index
【Jenkins 学习笔记】玩转持续集成与持续交付
jmeter的websocket插件安装和使用方法
SwiftUI * SwiftUI 4.0 全新的导航系统
What are the most popular automated testing tools in 2022?The most complete and most detailed of the entire network is here
grafana的panel点击title,没有反应,没有出现edit选项
快速乘写法
USB 触摸在竖屏时校准
opencv在图像上长按左键画矩形单击右键清除