UVA 465 - Overflow
本题主要是作了个高精度加法,乘法运算。代码还够长,题中我忽略了sscanf()得用法,要注意一些。还有就是复杂度的计算在这里显得重要了些,还得在这方面加把劲。
代码如下(C/C++):
#include<stdio.h>
#include<string.h>
#define MAXN 20000
char a[MAXN], b[MAXN],s[MAXN],y[2];
int A[MAXN], B[MAXN], S[MAXN];
void decide()
{
long long a1, b1, s1;
sscanf(a,"%lld",&a1);
sscanf(b,"%lld",&b1);
sscanf(s,"%lld",&s1);
printf("%s %s %s\n",a,y,b);
if(a1 > 0x7fffffff) printf("first number too big\n");
if(b1 > 0x7fffffff) printf("second number too big\n");
if(s1 > 0x7fffffff) printf("result too big\n");
}
void a_b_mult()
{
memset(A, 0, sizeof(A));
memset(B, 0, sizeof(B));
memset(S, 0, sizeof(S));
int len1 = strlen(a);
for(int i = 0; i < len1; i ++)
A[len1-1-i] = a[i] - '0';
int len2 = strlen(b);
for(int j = 0; j < len2; j ++)
B[len2-1-j] = b[j] - '0';
for(int i = 0; i <= len2; i ++)
{
int c = 0;
for(int j = 0; j <= len1; j ++)
{
S[i + j] += B[i] * A[j] +c;
c = S[i + j] / 10;
S[i + j] %= 10;
}
}
int i;
for(i = MAXN; i > 0; i --)
if(S[i]) break;
for(int j = 0; j <= i; j ++)
s[j] = S[i - j] + '0';
s[i+1] = '\0';
decide();
}
void a_b_sum()
{
memset(A, 0, sizeof(A));
memset(B, 0, sizeof(B));
memset(S, 0, sizeof(S));
int len1 = strlen(a);
for(int i = 0; i < len1; i ++)
A[len1-1-i] = a[i] - '0';
int len2 = strlen(b);
for(int j = 0; j < len2; j ++)
B[len2-1-j] = b[j] - '0';
int t;
if(len1>len2) t = len1;
else t = len2;
int c = 0;
for(int k = 0; k <= t; k ++)
{
S[k] = A[k] + B[k] + c;
c = S[k] / 10;
S[k] %= 10;
}
int i;
for(i = MAXN; i > 0; i --)
if(S[i]) break;
for(int j = 0; j <= i; j ++)
s[j] = S[i - j] + '0';
s[i+1] = '\0';
decide();
}
void input()
{
while(scanf("%s%s%s",a,y,b) == 3)
{
if(y[0] == '+') a_b_sum();
else a_b_mult();
}
}
int main()
{
input();
return 0;
}