1001 A+B Format (20分) 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 Specification: Each input file contains one test case. Each case contains a pair of integers a and b where −10 6 ≤a,b≤10 6 . The numbers are separated by a space.
Output Specification: 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
#include<iostream> #include<sstream> #include<string> using namespace std; string itos(int num){ stringstream s; s<<num; return s.str(); } int main(){ int a,b,sum=0; cin>>a>>b; sum=a+b; string s; s=itos(sum); for(int i=0;i<s.length();i++){ cout<<s[i]; if(s[i]=='-'){ continue; } // s is began from the high position such as 4000, // begin as 4 not zero. if((i+1)%3==s.length()%3&&i!=s.length()-1){ cout<<","; } } return 0; }字符串流,这里用到最基础的功能,int转string类型,首先定义一个stringstream类型的变量s,将int型变量sum,输入流,输出转换后的字符串,返回到主函数。
JAVA做PAT一定要对输入输出流进行优化,不然会超时。