概述
A - A + B Problem II
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 998877665544332211Sample Output
Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
思路:对于这种大数问题,按位取数,字符串s1和s2,代表输入的数据,把字符串分别倒着存储到a和b,加法运算倒着相加,max是用来标记长度最长的字符串,但是考虑到进位的问题,所以max要多一步判断。
加法准则,从后往前加。
注: 提交多次格式错误,特别注意cnt的数据,它的初始数据为1,cnt代表第几组,当cnt!=T的时候,就代表要多输出一行空白,所以要多一步判断,更加要注意的是cnt++的位置,很容易出错。
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<stdlib.h>
#include<string.h>
using namespace std;
char s1[10000],s2[10000];
int a[10000],b[10000],c[10000];
int main(){
int T,i,j;
cin>>T;
int cnt=1;
for(int k=0;k<T;k++){
scanf("%s %s",s1,s2);
memset(c,0,sizeof(c));
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
int len1=strlen(s1);
int len2=strlen(s2);
for(i=0;i<len1;i++){
a[i]=s1[len1-i-1]-'0'; //把数字一个一个的倒着存储在数组中
}
for(i=0;i<len2;i++){
b[i]=s2[len2-i-1]-'0';
}
int max=len1>len2?len1:len2;
for(i=0;i<=max;i++){
int sum=a[i]+b[i]+c[i];
if(sum>=10){//如果两个数字相加大于10,就证明要进位
c[i]=sum-10;//c数组存放进位后的数字
c[i+1]++;//进位后,c数组下一位的数据要加1
}else{
c[i]=sum;//如果不用进位的话,直接把相加后的结果存在c数组中,方便输出
}
}
printf("Case %d:n",cnt);
printf("%s + %s = ",s1,s2);
if(c[max]==0){
max--; //前导0的判断
}
for(i=max;i>=0;i--){
cout<<c[i];
}
if(cnt!=T)
cout<<endl<<endl; //考虑到每两组数据间多一行空格
else
cout<<endl;
cnt++;
}
return 0;
}
Java代码
注:类名必须为Main,不能为其他,不然容易出错;包也不用导入,导入也出错
import java.util.Scanner;
import java.math.BigInteger;
public class Main {
public static void main(String args[]){
int cnt=0;
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
while(n!=0){
n--;
BigInteger a,b;
a=scan.nextBigInteger();
b=scan.nextBigInteger();
System.out.println("Case "+(++cnt)+":");
System.out.println(a+" + "+b+" = "+a.add(b));
if(n!=0)
System.out.println();
}
}
}
最后
以上就是和谐月饼为你收集整理的A - A + B Problem II的全部内容,希望文章能够帮你解决A - A + B Problem II所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复