高精度乘法
作者:
浩然正气
,
2024-11-14 10:38:47
,
所有人可见
,
阅读 4
高精度乘法C
语言
#include <stdio.h>
#include <string.h>
#define N 100010
void mul(char str[], int* u, char high_mul[])
{
int b = *u;
int len = strlen(str);
// 1. 将字符数组转换成整数数组,第0位存储个位数字
int a[N] = {0};
for (int i = 0; i < len; i ++ )
a[i] = str[len - i - 1] - '0';
// 2. 乘法过程
int index = 0;
int t = 0; // 进位
int res[N] = {0};
for (int i = 0; i < len || t; i ++ )
{
if (i < len) t = (a[i] * b) + t;
res[index ++] = t % 10;
t = t / 10;
}
// 3. 去除前导0
int high = 0;
int zero_index = 1;
for (int i = index - 1; i >= 0; i -- )
{
if (res[i] == 0 && zero_index)
continue;
else
{
zero_index = 0;
high_mul[high ++] = res[i] + '0';
}
}
if (zero_index)
strcpy(high_mul, "0");
}
int main()
{
int b;
char str[N] = "";
char high_mul[N] = "";
scanf("%s", str);
scanf("%d", &b);
mul(str, &b, high_mul);
puts(high_mul);
return 0;
}