由于C语言定义的数值型的数据范围有限,
所以不能用简单的加减法来计算数据特别大的数;
这时候就要用到: 字符数组来进行计算;
字符数组:
通过定义两个数组( 一个为 int 型,一个为 char 型 );
先将输入的数字用 char 型数组存储,之后再用语句:
( int ) a[ i ]= ( char ) b[ i ] - ' 0 ' ;
将输入的数字字符按顺序存入到 int 型数组中( 按 a[ 0 ] 为首位存储 );
例( 此数组可存储2000位的数 ):
#include<stdio.h>
#include<string.h>
int main()
{
int i,a[2000],lenb;
char b[2000];
scanf("%s",&b);
lenb=strlen(b);
for(i=0; i<lenb; i++) a[i]=b[i]-'0';
for(i=0; i<lenb; i++) printf("%d",a[i]);
}
大数 A+B 的算法:
通过对数组A 和数组 B的每一位相加,并且判断
若和大于十的时候,和减去十,并且下一位加一即可;
题目:
A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 260741 Accepted Submission(s): 50418
Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
Sample Input
2 1 2 112233445566778899 998877665544332211
Sample Output
Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
AC代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
char a[2200],b[2200];
int main()
{
int p,n,numa[2200],numb[2200];
scanf("%d",&n);
for(p=0; p<n; p++)
{
scanf("%s%s",&a,&b);
int i,j,lena,lenb;
memset(numa,0,sizeof(numa));//重置并归零数组!!!!!;
memset(numb,0,sizeof(numb));
lena=strlen(a);
lenb=strlen(b);
for(j=0,i=lena-1; i>=0; i--) numa[j++]=a[i]-'0';//字符数组
for(j=0,i=lenb-1; i>=0; i--) numb[j++]=b[i]-'0';
for(i=0; i<2200; i++)
{
numa[i]+=numb[i];//对应位相加;
if(numa[i]>=10)//若和超过10,仅保留个位,下一位加一;
{
numa[i]-=10;
numa[i+1]++;
}
}
for(i=2199; ((i>=0)&&numa[i]==0); i--);//除去数组后多余的 '0 ',并且把定位值 i 放在最后( 从后向前输出 )!!!!!;
if(i>=0)
{
printf("Case %d:\n",p+1);
printf("%s + %s = ",a,b);
for(; i>=0; i--)
{
int q;
printf("%d",numa[i]);
if(i==0&&p!=n-1) printf("\n");
}
}
printf("\n");
}
return 0;
}