PAT Advanced 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 −. 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<stack> using namespace std; int main() { long a,b; cin>>a>>b; long res=a+b; if(res==0){ cout<<0; system("pause"); return 0; } bool sign; int m=0; if(res<0) { sign=false; res=-res; } else sign=true; stack<char> sta; while(res!=0){ m++; sta.push(res%10+'0'); res/=10; if(m%3==0) sta.push(','); } if(sta.top()==',') sta.pop(); if(!sign) cout<<"-"; while(!sta.empty()){ cout<<sta.top(); sta.pop(); } system("pause"); return 0; }