问题链接
问题描述
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).
输入两个整数a和b,计算a和b的和,并以一定格式输出(每三位为一组,以逗号’,'分隔)
样例输入
-1000000 9
样例输出
-999,991
算法思想
由于数据范围都在 − 1 0 6 ≤ a , b ≤ 1 0 6 -10^6\le a,b\le10^6 −106≤a,b≤106范围内,所以可以直接求和,只要在输出的时候注意格式就行:
心得体会
这道题主要是注意特殊情况:1. 和为负数的情况 2. 补充前导0的情况 3. 使用栈时注意栈是否为空,避免段错误。
完整代码
#include
#include
#include
using namespace std;
int main()
{
//输入两个数
int a,b;
cin>>a>>b;
int c = a+b;
//保留符号位
int flg = c<0;
//取绝对值
c = abs(c);
stacks;
//结果为0
if(c==0) {
cout<<"0";
return 0;
}
while(c) {
s.push(c%1000);
c /= 1000;
}
if(flg){
cout<<"-";
}
cout<99) {
cout<9) {
cout<<"0"<