HDU 1002 A + B Problem II 大数相加
java 水过
import java.io.*; import java.util.*; import java.math.BigInteger; public class aa { public static void main( String args[] ) { BigInteger a,b; Scanner in = new Scanner ( System.in ); int t = in.nextInt(); for( int i = 1; i <= t; ++i ) { in.hasNext(); a = in.nextBigInteger();b = in.nextBigInteger(); BigInteger c = a.add(b); System.out.println( "Case "+i+":" ); System.out.println( a+" + "+b+" = "+c ); if( i != t ) System.out.println( ); } } }
刚刚开始系统的做大数,又把这题水了一遍,不过太大意的,输出格式错了几次,下次就算是做现题都要认真;
因为"大数"可能很大,所以long long和double可能都存不下,所以要用数组来把他们存下来,然后一位一位来计算;而且要从个位数即数组的最后一位加起
#include<stdio.h> #include<string.h> const int Maxsize = 1024; char num[Maxsize],a[Maxsize]; int sum[Maxsize]; int main( ) { int t,k; scanf( "%d\n",&t ); k = t; while( k-- ) { memset( sum,0,sizeof( sum ) ); for( int i = 0; i < 2; ++i ) { scanf( "%s",num ); int len = strlen( num ); for( int i = 0; i < len; ++i )//核心 { sum[i] += num[len - i - 1] - '0'; if( sum[i] > 9 ) { ++sum[i+1]; sum[i] -= 10; } } if( i == 0 ) strcpy( a,num ); } int j = Maxsize - 1; while( !sum[j] ) --j; printf( "Case %d:\n",t - k ); printf( "%s + %s = ",a,num ); for( ; j >= 0; --j ) printf( "%d",sum[j] ); puts( "" ); if( k )puts( "" ); } return 0; }
本人还是新手 ,转载请注明来自Lvsi‘s home