# 大整数，四则运算

// 四则运算，负数情况未处理
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

struct bignum
{
int d[1000];
int len;
bignum()
{
memset(d, 0, sizeof(d));
len = 0;
}
};

bignum change(char str[])
{
bignum a;
a.len = strlen(str);
for(int i = 0; i < a.len; i++)
a.d[i] = str[a.len - 1 - i] - '0';
return  a;
}

int compare(bignum a, bignum b)
{
if(a.len > b.len) return 1;
else if(a.len < b.len) return -1;
else
{
for(int i = a.len-1; i >= 0; i--)
{
if(a.d[i] > b.d[i])
return 1;
else if(a.d[i] < b.d[i])
return -1;
}
return 0;
}
}

{
bignum 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;
}

bignum sub(bignum a, bignum b)
{
if(compare(a, b) < 0)
{
swap(a, b);
printf("-");
}
bignum 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-1] == 0)
c.len--;
return c;
}

bignum multi(bignum a, int b)
{
bignum c;
int carry = 0;
for(int i = 0; i < a.len; i++)
{
int temp = a.d[i] * b + carry;
c.d[c.len++] = temp % 10;
carry = temp / 10;
}
while(carry != 0)
{
c.d[c.len++] = carry % 10;
carry /= 10;
}
return c;
}

bignum divide(bignum a, int b, int &r)
{
bignum c;
c.len = a.len;
for(int i = a.len-1; i >= 0; i--)
{
r = r * 10 + a.d[i];
if(r < b) c.d[i] = 0;
else
{
c.d[i] = r / b;
r = r % b;
}
}
while(c.len - 1 >= 1 && c.d[c.len-1] == 0)
c.len--;
return c;
}

void print(bignum a)
{
for(int i = a.len-1; i >= 0; i--)
printf("%d",a.d[i]);
printf("\n");
}

int main()
{
char str1[1000], str2[1000];
scanf("%s%s",str1, str2);
bignum a = change(str1);
bignum b = change(str2);
print(sub(a, b));
int k = 10;
printf("bignum a * 10 = ");
print(multi(a, k));
int r = 0;
printf("bignum a / 10 = ");
print(divide(a, k, r));

return 0;
}
• 点赞 1
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

xiao酱油

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
03-05 162
03-25 2399

10-21 3024
12-17 7252
10-11 3374
04-17 1万+
08-01 5321
11-07 4475
03-04 1322
03-10 1992