当前位置:网站首页>LeetCode43. String multiplication (this method can be used to multiply large numbers)
LeetCode43. String multiplication (this method can be used to multiply large numbers)
2022-08-11 05:45:00 【FussyCat】
leecode题链接:LeetCode43.字符串相乘
题目描述:
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式.
示例 1:
输入: num1 = “2”, num2 = “3”
输出: “6”
示例 2:
输入: num1 = “123”, num2 = “456”
输出: “56088”
说明:
num1 和 num2 的长度小于110.
num1 和 num2 只包含数字 0-9.
num1 和 num2 均不以零开头,除非是数字 0 本身.
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理.
解题思路:
字符串相乘,vertical multiplication,Multiply and add while converting to characters,The solution is shown in the notes.
以下用C语言实现:
#define NUM(ch) ((ch) - '0')
#define CHAR(n) ((n) + '0')
char * multiply(char * num1, char * num2){
if (num1 == NULL || num2 == NULL) {
return NULL;
}
int size1 = strlen(num1);
int size2 = strlen(num2);
if ((size1 == 1 || size2 == 1) && (num1[0] == '0' || num2[0] == '0')) {
/* One of the two numbers is0,则乘积为0 */
return "0";
}
char *result = (char *)malloc(size1 + size2 + 1);
memset(result, '0', size1 + size2 + 1);
int i, j, tmp0, tmp1;
result[size1 + size2] = '\0';
for (i = size1 - 1; i >= 0; i--) {
/* 从个位数开始算 */
for (j = size2 - 1; j >= 0; j--) {
/* 从个位数开始算 */
tmp1 = NUM(result[i + j + 1]) + NUM(num1[i]) * NUM(num2[j]); /* 第i位的num1和第j位的num2相乘, tmp1最大为两位数 */
result[i + j + 1] = CHAR(tmp1 % 10); /* The single digit of a two-digit number */
tmp0 = tmp1 / 10 + NUM(result[i + j]); /* Tens of two digits+The number currently saved,求和 */
result[i + j] = CHAR(tmp0 % 10); /* and single digits */
if ( i + j - 1 >= 0) {
result[i + j - 1] = CHAR(tmp0 / 10 + NUM(result[i + j - 1])); /* and the ten digits+The number currently saved,求和 */
}
}
}
for (i = 0; i < size1 + size2; i++) {
if (result[i] != '0') {
/* Remove the prefix as 0的情况,Find the last one in the prefix0的位置 */
break;
}
}
return (result + i);
}
边栏推荐
猜你喜欢
Keras与tensorflow 使用基础
Flask框架学习:模板渲染与Get,Post请求
(1) Construction of a real-time performance monitoring platform (Grafana+Influxdb+Jmeter)
(三)性能实时监控平台搭建(Grafana+Prometheus+Node_explorer+Jmeter)
RK3399上的Tengine实践笔记
【动态代理】CGLIB 动态代理的使用及原理
吃瓜教程task02 第3章 线性模型
pip 国内源下载
看完这篇博客之后,含着泪学会了TCP/IP
(2) Construction of a real-time performance monitoring platform (Grafana+Prometheus+Jmeter)
随机推荐
pytorch中tensor 生成的函数
第二篇 DS5 Armv8 样例工程报错之GCC编译
ClionIDE通过指定编译器编译
c 指针学习(1)
LeetCode1166.设计文件系统
字符与字符串
利用rand函数随机生成uuid
postman脚本的应用
C语言学习记录--变量基本类型和内存大小
Apache Commons OGNL语法说明_翻译
Django--20 implements Redis support, context, and interaction of context and interface
task06 PyTorch生态
The most complete installation tutorial of Pytorch (one step)
做款好喝的茶饮~
【网站小白】Hibernate插入数据成功,不报错,但是数据库中没有值
[转载]Verilog testbench总结
[Verilog] I2S Master Test Bench
【win10+cuda7.5+cudnn6.0安装caffe④】安装pycaffe
博客帮助文档
吃瓜教程task05 第6章 支持向量机