【每天一道PAT】1001 A+B Format
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 −106≤a,b≤106. 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.
思路
计算得到两数总和后,将每位数字存入栈中。
再将栈中的数字依次打印出来,同时判断栈中剩下的数字整除是否为3,如果是打印“,”。
#include <stdio.h>
#include <stack>
using namespace std;
int main()
{
int a, b, c;
stack<int> st;
scanf("%d%d",&a,&b);
c = a+ b;
if(c<0){printf("-"); c = 0-c;}
do{
st.push(c%10);
c /=10;
}while(c !=0);
while(st.empty() == false)
{
printf("%d",st.top());
st.pop();
if((st.size()%3 ==0)&&(st.size()!=0)) printf(",");
}
}