HDU 1002 A + B Problem II(大数加法,C,Java两个版本)
发布时间:2021-05-25 15:09:41 所属栏目:大数据 来源:网络整理
导读:?? A + B Problem II Time Limit: 2000/1000 MS (Java/Others)????Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 300365????Accepted Submission(s): 57917 Problem Description I have a very simple problem for you. Given two inte
|
?? A + B Problem IITime Limit: 2000/1000 MS (Java/Others)????Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 300365????Accepted Submission(s): 57917Problem 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. ? InputThe 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.? OutputFor 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 Input2 1 2 112233445566778899 998877665544332211? Sample OutputCase 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 2222222222222221110? AuthorIgnatius.L原题链接 :http://acm.hdu.edu.cn/showproblem.php?pid=1002 大数加法,不解释! AC代码#include <cstdio>
#include <cstring>
#define maxn 1005
int main()
{
int n;
int da[maxn],db[maxn],c[maxn];
char a1[maxn],a2[maxn];
scanf("%d",&n);
for(int kase=1; kase<=n; kase++)
{
scanf("%s",a1);
scanf("%s",a2);
printf("Case %d:n",kase);
printf("%s + %s = ",a1,a2);
int len1=strlen(a1);
int len2=strlen(a2);
memset(da,sizeof(da));
memset(db,sizeof(db));
memset(c,sizeof(c));
int len=len1>len2?len1:len2;
int k=0;
for(int i=len1-1; i>=0; i--)
da[k++]=a1[i]-'0';
k=0;
for(int i=len2-1; i>=0; i--)
db[k++]=a2[i]-'0';
int carry=0;
for(int i=0; i<len; i++)
{
c[i]=(da[i]+db[i]+carry)%10;
carry=(da[i]+db[i]+carry)/10;
}
bool start=false;//此变量用于跳过多余的0
for(int i=len; i>=0; i--)
{
if(start)
printf("%d",c[i]);//如果跳过多余的0,则输出
else if(c[i])
{
printf("%d",c[i]);
start=true;//遇到第一个非0值,则跳过多余的0
}
}
printf("n");
if(kase!=n)
printf("n");
}
}<span style="font-size:18px;color:#3333ff;">
</span>
Java大数import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
for(int i=1;i<=n;i++){
BigInteger a = sc.nextBigInteger();
BigInteger b = sc.nextBigInteger();
System.out.println("Case "+i+":");
System.out.println(a+" + "+b+" = "+a.add(b));
if(i!=n){
System.out.println();
}
}
}
}
(编辑:荆州站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

