[HDU] [1002] A + B Problem II

Problem Description

Loading...

Problem Analysis

Big Number addition problem
Actually, it’s just using arrays to simulate addition and subtraction of numbers
Actually, thinking about it, it’s not that complicated
But I did struggle with it for quite a while back then

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<stdio.h>
#include<string.h>
int main() {
	int i,T,k,lmax,a[1010],b[1010],sum[1010];
	char x[1010],y[1010];
	scanf("%d",&T);
	for(i=0; i<T; i++) {
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		memset(x,0,sizeof(x));
		memset(y,0,sizeof(y));
		memset(sum,0,sizeof(sum));
		scanf("%s %s",x,y);
		int la=strlen(x),lb=strlen(y);
		for(k=0; k<la; k++) {
			a[k]=x[la-k-1]-'0';
		}
		for(k=0; k<lb; k++) {
			b[k]=y[lb-k-1]-'0';
		}
		lmax=lb;
		if(la>lb)
			lmax=la;
		for(k=0; k<lmax; k++) {
			if(sum[k]+a[k]+b[k]<10)
				sum[k]=sum[k]+a[k]+b[k];
			else {
				sum[k]=sum[k]+a[k]+b[k]-10;
				sum[k+1]=1;
			}
		}
		printf("Case %d:\n",i+1);
		if(sum[lmax]==1)
			lmax=lmax+1;
//		for(k=lmax; k!=0; k--) {
//			if(sum[k-1]==0)
//				lmax--;
//			if(sum[k-1]!=0)
//				break;
//		}
//		if(lmax==0)
//			lmax=1;
//去除结果前面的0 不知道需不需要加 
		printf("%s + %s = ",x,y);
		for(k=lmax; k!=0; k--)
			printf("%d",sum[k-1]);
		printf("\n");
		if(i!=T-1)
			printf("\n");
	}
	return 0;
}

Now I probably wouldn’t write it so complicatedly…

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...