用整型数组表示10进制大整数(超过2^32的整数),数组的每个元素存储大整数的一位数字,实现大整数的加减法。
时间: 2024-02-01 14:14:44 浏览: 33
下面是用C++实现的大整数加减法的代码,其中使用了整型数组来存储大整数的每一位数字。加法和减法的实现都比较类似,主要是对进位和借位的处理。
```c++
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 10010; // 数组最大长度
// 将字符串转换成整型数组
void strToIntArray(char s[], int a[]) {
int len = strlen(s);
for (int i = 0; i < len; i++) {
a[i] = s[len - 1 - i] - '0'; // 从低位到高位存储
}
}
// 将整型数组转换成字符串
void arrayToStr(int a[], char s[]) {
int len = 0;
while (a[len] != 0) len++;
for (int i = 0; i < len; i++) {
s[i] = a[len - 1 - i] + '0'; // 从高位到低位输出
}
s[len] = '\0';
}
// 大整数加法
void bigIntAdd(int a[], int b[], int c[]) {
int carry = 0; // 进位
for (int i = 0; a[i] != 0 || b[i] != 0; i++) {
int sum = a[i] + b[i] + carry;
carry = sum / 10;
c[i] = sum % 10;
}
if (carry > 0) {
c[strlen((char*)a)] = carry;
}
}
// 大整数减法
void bigIntSub(int a[], int b[], int c[]) {
int borrow = 0; // 借位
for (int i = 0; a[i] != 0 || b[i] != 0; i++) {
int sub = a[i] - b[i] - borrow;
if (sub < 0) {
sub += 10;
borrow = 1;
} else {
borrow = 0;
}
c[i] = sub;
}
}
int main() {
char s1[MAXN], s2[MAXN];
int a[MAXN] = {0}, b[MAXN] = {0}, c[MAXN] = {0};
cin >> s1 >> s2;
strToIntArray(s1, a);
strToIntArray(s2, b);
// 计算 a + b,并将结果存储到 c 中
bigIntAdd(a, b, c);
char s3[MAXN];
arrayToStr(c, s3);
cout << s3 << endl;
// 计算 a - b,并将结果存储到 c 中
bigIntSub(a, b, c);
arrayToStr(c, s3);
cout << s3 << endl;
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)