大整数的存储
整数的高位存在数组的高位,整数的低位存在数组的低位 A + B
#include<iostream>
#include<cstring>
using namespace std;
struct bign{
int d[1000];
int len;
bign(){
memset(d, 0, sizeof(d));
len = 0;
}
};
bign change(char str[]){
bign a;
a.len = strlen(str);
for(int i = 0; i < a.len; i++){
a.d[i] = str[a.len - 1 - i] - '0';
}
return a;
}
bign add(bign a, bign b){
bign c;
int carry = 0;
for (int i = 0; i < a.len || i < b.len; i++){
int temp = a.d[i] + b.d[i] + carry;
c.d[c.len++] = temp % 10;
carry = temp / 10;
}
if(carry != 0) c.d[c.len++] = carry;
return c;
}
void show(bign c){
for (int i = c.len - 1; i >= 0; i--){
cout << c.d[i];
}
}
int main(){
char str1[1000], str2[1000];
cin >> str1 >> str2;
bign a = change(str1);
bign b = change(str2);
show(add(a, b));
return 0;
}
加法中的进位
struct bign{
int d[1000];
int len;
bign(){
memset(d, 0, sizeof(d));
len = 0;
}
};
bign add(bign a, bign b){
bign c;
int carry = 0;
for(int i = 0; i < a.len || i < b.len; i++)
{
int temp = a.d[i] + b.d[i] + carry;
c.d[c.len++] = temp % 10;
carry = temp / 10;
}
if(carry != 0) c.d[c.len++] = carry;
return c;
}
A-B
bign sub(bign a, bign b){
bign c;
for (int i = 0; i < a.len || i < b.len; i++){
if(a.d[i] < b.d[i]){
a.d[i + 1]--;
a.d[i] += 10;
}
c.d[c.len++] = a.d[i] - b.d[i];
}
while(c.len - 1 >= 1 && c.d[c.len--] == 0{
c.len--;
}
return c;
}
A * B
bign add(bign a, bign b){
bign c;
int carry = 0;
for(int i = 0; i < a.len || i < b.len; i++)
{
int temp = a.d[i] * b.d[i] + carry;
c.d[c.len++] = temp % 10;
carry = temp / 10;
}
while(carry != 0)
{
c.d[c.len++] = carry % 10;
carry /= 10;
}
return c;
}
|