天天看點

程式設計題目:PAT(Advanced Level) Practice 1001. A+B Format (20) 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;

}