当前位置:网站首页>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);
}
边栏推荐
猜你喜欢
家·谱——人脸识别家谱系统
Solidrun hummingboard制作SD卡
【win10+cuda7.5+cudnn6.0安装caffe④】安装pycaffe
(三)性能实时监控平台搭建(Grafana+Prometheus+Node_explorer+Jmeter)
吃瓜教程task02 第3章 线性模型
Flask框架学习:模板继承
简单做份西红柿炒蛋778
pytorch安装笔记——Pytorch在conda+CUDA10.2环境安装task01
Flask框架学习:模板渲染与Get,Post请求
Flask framework learning: template rendering and Get, Post requests
随机推荐
CSDN 社区内容创作规范
做款好喝的茶饮~
DS220702-0707作业
面试宝典一: code题目记录
(3) Construction of a real-time performance monitoring platform (Grafana+Prometheus+Node_explorer+Jmeter)
第4章 复合类型-2(指针)
原生态mongo连接查询代码
c指针学习(2)
Who am I ?
(1) Docker installs Redis in practice (one master, two slaves, three sentinels)
【背包】采药题解
win下clion打包的.exe文件在无运行环境的电脑运行显示缺失各种.dll
普林斯顿概率论读本读书笔记(阅读中......)
win下Anaconda(环境配置等)和pycharm安装详细教程
C语言之EOF、feof函数、ferror函数
Pytorch最全安装教程(一步到位)
利用rand函数随机生成uuid
【CSDN21天学习挑战赛】第一天,配置环境外加实现mnist手写数字识别
二、Jmeter 核心配置文件
CentOS卸载Oracle 11gR2(x64)_转载