对于20位以上的超长整数无法用int、long等基本类型表示,但可以考虑用字符串实现。 本关任务:编写程序,基于字符串实现对超长整数的加法运算和减法运算,输入两个超长整数和运算符(+或-),输出运算结果。 例如:输入123456789012345678901 + 123,输出123456789012345679024。 要求:输入的两个超长整数都是非负整数,并且长度都小于100位。对于减法运算,如果运算结果为负数要在前面加上负号。并且运算结果要去掉前导0,例如运算结果如果是000123,要变成123输出。 提示 对于加法,考虑先把两个数对齐,再按位加(要考虑进位),运算结果以字符串形式输出。 对于减法,先比较被减数和减数的大小,如果被减数小于减数,则需要交换被减数和减数,然后再按位减(要考虑借位)。 测试说明 平台会对你编写的代码进行测试: 测试输入:123456789012345678901 + 123 预期输出:123456789012345679024,用c语言写
时间: 2024-03-10 18:47:42 浏览: 214
以下是基于字符串实现超长整数加减法的C语言代码:
```c
#include <stdio.h>
#include <string.h>
// 去掉字符串前导0
char* removeLeadingZero(char* s) {
while (strlen(s) > 1 && s[0] == '0') {
strcpy(s, s + 1);
}
return s;
}
// 将两个字符串对齐,短字符串前面补0
void alignStrings(char* s1, char* s2) {
int l1 = strlen(s1), l2 = strlen(s2);
if (l1 < l2) {
char* temp = (char*) malloc(sizeof(char) * (l2 - l1 + 1));
memset(temp, '0', l2 - l1);
temp[l2 - l1] = '\0';
strcat(temp, s1);
strcpy(s1, temp);
free(temp);
} else if (l1 > l2) {
char* temp = (char*) malloc(sizeof(char) * (l1 - l2 + 1));
memset(temp, '0', l1 - l2);
temp[l1 - l2] = '\0';
strcat(temp, s2);
strcpy(s2, temp);
free(temp);
}
}
// 超长整数加法
char* addLongInteger(char* s1, char* s2) {
// 将两个字符串对齐
alignStrings(s1, s2);
int l = strlen(s1);
char* res = (char*) malloc(sizeof(char) * (l + 2));
int carry = 0;
// 逐位相加,注意进位
for (int i = l - 1; i >= 0; i--) {
int temp = s1[i] - '0' + s2[i] - '0' + carry;
carry = temp / 10;
res[i + 1] = temp % 10 + '0';
}
// 如果还有进位,最高位加1
if (carry) {
res[0] = '1';
res[l + 1] = '\0';
} else {
res[l] = '\0';
}
// 去掉前导0
return removeLeadingZero(res);
}
// 超长整数减法
char* subLongInteger(char* s1, char* s2) {
// 比较大小,如果被减数小于减数,则交换两个数
if (strlen(s1) < strlen(s2) || (strlen(s1) == strlen(s2) && strcmp(s1, s2) < 0)) {
char* temp = s1;
s1 = s2;
s2 = temp;
}
// 将两个字符串对齐
alignStrings(s1, s2);
int l = strlen(s1);
char* res = (char*) malloc(sizeof(char) * (l + 1));
int borrow = 0;
// 逐位相减,注意借位
for (int i = l - 1; i >= 0; i--) {
int temp = s1[i] - s2[i] - borrow;
if (temp < 0) {
temp += 10;
borrow = 1;
} else {
borrow = 0;
}
res[i] = temp + '0';
}
// 去掉前导0
return removeLeadingZero(res);
}
int main() {
char s1[101], s2[101], op;
scanf("%s %c %s", s1, &op, s2);
if (op == '+') {
printf("%s\n", addLongInteger(s1, s2));
} else {
printf("%s%s\n", strcmp(s1, s2) < 0 ? "-" : "", subLongInteger(s1, s2));
}
return 0;
}
```
输入格式为 "被加数 运算符 加数",例如 "123456789012345678901 + 123",输出结果为运算结果的字符串形式。
阅读全文
相关推荐














