码迷,mamicode.com
首页 > 其他好文 > 详细

杭电OJ 1002 大数相加

时间:2015-08-08 22:54:53      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:杭电oj 1002   大数相加   

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
 
输出格式是:结果之间空一行,最后的结果后面无空行,但是光标一定得移动到结果的下一行,否则PE错误。(鄙视这种不明说而纯粹需要靠眼力观察得出的格式要求)

public static void bigNumAdd(){
		Scanner s = new Scanner(System.in);
		int a = s.nextInt();
		int b = 0;
		int c[] = null;
		int d[] = null;
		int sum[] = null;
		while(++b <= a){
			c = new int[1000];
			d = new int[1000];
			sum = new int[1001];
			String ss = s.next();
			String bb = s.next();	
			int chlen = ss.length();
			int shlen = bb.length();
			char ch[] = ss.toCharArray();
			char sh[] = bb.toCharArray();
			
			System.out.println("Case "+b+":");
			for(int i=0;i<chlen;i++){
				c[i] = Integer.parseInt(ch[i]+"");
				System.out.print(c[i]);
			}
			System.out.print(" + ");
			for(int j=0;j<shlen;j++){
				d[j] = Integer.parseInt(sh[j]+"");
				System.out.print(d[j]);
			}
			System.out.print(" = ");
			int sumlen = 1001;
			while(chlen-1 >=0 || shlen -1 >=0){//将两个数组的值相加,结果放到第三个数组中
				if(chlen <= 0 && shlen > 0){
					sum[--sumlen] = d[--shlen];
				}
				if(chlen > 0 && shlen <= 0){
					sum[--sumlen] = c[--chlen];
				}
				if(chlen > 0 && shlen > 0)
				{
					sum[--sumlen] = c[--chlen] + d[--shlen];
				}
			}
			for (int k = 1000; k > 0; k--) {//对第三个数组的结果进行处理,特别是超出10的部分。
				if ( sum[k] > 9) {
					sum[k] = sum[k] - 10;
					sum[k - 1]++;
				}
			}
			int flag = 0;
			for(int q=0;q<sum.length;q++){
				if(sum[q] == 0 && flag == 0){//对于默认填充0的数组元素,不输出。
					continue;
				}
				flag =1;
				System.out.print(sum[q]);
			}
			System.out.println();//万恶的系统格式处理
			if(a !=b){
				System.out.println();
			}
		}//while
	}
运行结果:
2
12345 11
Case 1:
12345 + 11 = 12356

11 1
Case 2:
11 + 1 = 12



版权声明:本文为博主原创文章,转载请注明出处:http://blog.csdn.net/lingzhm

杭电OJ 1002 大数相加

标签:杭电oj 1002   大数相加   

原文地址:http://blog.csdn.net/lingzhm/article/details/47362591

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!