高精度加法
作者:
浩然正气
,
2024-11-14 08:27:16
,
所有人可见
,
阅读 3
高精度加法C
语言
#include <stdio.h>
#include <string.h>
#define N 100010
void add(char str1[], char str2[], char add_high[])
{
int index = 0;
int len1 = strlen(str1);
int len2 = strlen(str2);
int a[N] = {0};
int b[N] = {0};
int res[N] = {0};
// 1. 将字符数组转换成整数数组,第0位存储个位数字
for (int i = 0; i < len1; i ++ )
a[i] = str1[len1 - 1 - i] - '0';
for (int i = 0; i < len2; i ++ )
b[i] = str2[len2 - 1 - i] - '0';
// 2. 加法过程
int t = 0;
for (int i = 0; i < len1 || i < len2; i ++ )
{
if (i < len1) t += a[i];
if (i < len2) t += b[i];
res[index ++] = t % 10;
t /= 10;
}
// 如果还有进位,补最高位
if (t != 0)
res[index ++] = t;
// 去除前导0
int zero_index = 1;
int happy = 0;
for (int i = index - 1; i >= 0; i -- )
{
if (res[i] == 0 && zero_index == 1)
continue;
else
{
zero_index = 0; // 不是前导0
add_high[happy ++] = res[i] + '0';
}
}
if (zero_index == 1)
strcpy(add_high, "0");
}
int main()
{
char str1[N] = "";
char str2[N] = "";
char add_high[N] = "";
scanf("%s", str1);
scanf("%s", str2);
add(str1, str2, add_high);
puts(add_high);
return 0;
}