编程题目:PAT(Advanced Level) Practice 1001. A+B Format (20)

1001. A+B Format (20)

时间限制
400 ms
内存限制
32000 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Calculate a + b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

Input

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input
-1000000 9
Sample Output
-999,991
       本题并不难,要注意的就是对于输出格式的控制。参考代码如下,其实写的有些繁琐了,直接借助1000这个值来控制输出应该更便捷。
/*
http://pat.zju.edu.cn/contests/pat-a-practise/1001
*/

#include<iostream>
#include<vector>
#include<stack>
using namespace std;

int main()
{
	stack<int> v;
	int a ,b ;
	cin>>a>>b;
	int c= a + b;
	int sign=0;
	if( c==0 )//等于0
	{
		cout<<"0"<<endl;
	}
	if(c<0)//负数的处理
	{
		sign = 1;//表负数
		c = 0-c;
	}
	while(c!=0)
	{
		int temp = c%10;
		v.push(temp);
		c/=10;
	}

	///控制输出
	if(sign==1)
		cout<<'-';
	int remind = v.size()%3;
	int flag = 0;
	while(remind>0)
	{
		flag = 1;
		int out = v.top();
		cout<<out;
		v.pop();
		remind--;
	}
	if(flag ==1 && !v.empty())
		cout<<',';
	int count = 0;
	while(!v.empty())
	{
		if(count%3==0 && count>0)
			cout<<",";
		int out = v.top();
		cout<<out;
		v.pop();
		count++;
		
	}
	
	system("pause");
	return 0;

}






你可能感兴趣的:(level,Advanced,pat,1001)