题目
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.
Sample Input:
-1000000 9
Sample Output:
-999,991
解析
这题大意是让输入a和b,将结果按照每3位一组用逗号分隔输出,比如输入-1000000和9,那么得到和为-999991,按格式输出为-999,991。
我们可以考虑使用一个数组来模拟栈,对a+b的值x每取一次模就入一次栈,这样就可以把结果的低位放在栈底,高位放在栈顶,输出的时候从栈顶开始,先输出高位再输出低位。
由于a和b不超过10^6,所以我们构造一个7位的数组就够了。
源码
#include <iostream>
using namespace std;
int main(){
int a,b;
bool flag=false;//标识结果正负
cin>>a>>b;
int x=a+b;
// cout<<"x="<<x<<endl;
if(x<0){
x=-x;flag=true;//x为负时取绝对值
}else if(x==0){
cout<<0;
return 0;//x为0时直接输出并结束
}
int i=-1;//i指示栈顶,初始栈为空,i为-1
int stack[7];//模拟栈,使低位先入栈并后输出
while(x>0&&i<7){
stack[++i]=x%10;//入栈
x=x/10;
}
if(flag){stack[i]=-stack[i];} //符号控制,如果和值为负值,则使第一位(高位)为负
while(i>=0){
cout<<stack[i];//出栈
if(i%3==0&&i)cout<<",";//格式控制
i--;
}
return 0;
}
测试结果
注:重点测试结果为0的情况、结果的位数不是3的整数倍的情况,和结果为负值的情况。