杭电OJ1002

A + B Problem II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 334538    Accepted Submission(s): 64900


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
 
我的代码呢,是采用字符串类来使用的,首先设置三个字符串a,b,c来代表输入的两个数字,和输出的一个数字。其中,三个整型的变量i,j,k分别为字符串a的长度,字符串b的长度,每一位相加时进位的大小(例如:9+9=18,那么k就为1)。n为题中要求的变量,l 为输出是Case后的数字

好了,C++代码如下:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
	string a, b, c;
	int i, j, k, l = 0, n;
	cin >> n;
	while (cin >> a >> b) {
		i = a.length();
		j = b.length();
		k = 0;//每次的循环都必须要置零
		c = "";//每次循环都需要把字符串置空,否则上一次的数字将会留下,造成错误的输出
		while (j > 0 && i > 0) {
			c.insert(0,1,(char)((a[i - 1] - '0' + b[j - 1] - '0' + k) % 10 + '0'));
			k = (a[i-1] - '0' + b[j-1] - '0'+k) / 10;
			i--;
			j--;
		}
		/*以下是一个判断加循环的结构,主要解决,a,b的长度不相同的情况*/
		if (i > 0) {
			while (i > 0) {
				c.insert(0, 1, (char)((a[i - 1] - '0' + k) % 10 + '0'));
				k = (a[i - 1] - '0' + k) / 10;
				i--;
			}
		}
		else if(j > 0){
			while (j > 0) {
				c.insert(0, 1, (char)((b[j - 1] - '0' + k) % 10 + '0'));
				k = (b[j - 1] - '0' + k) / 10;
				j--;
			}
		}
		/*判断所有位都相加完了,但还是有进位的情况,例如第二个案例输出的例子*/
		if (k > 0) {
			c.insert(0, 1, (char)(k + '0'));
		}
		cout << "Case " << ++l << ":" << endl << a << " + " << b << " = " << c;
		if (l<n) {
			cout << endl<<endl;
		}
		else {
			cout << endl;
			break;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值