问题链接
问题描述
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范围内,所以可以直接求和,只要在输出的时候注意格式就行:
- 定义变量c为a和b的和
- 将c求余,余数存入栈s,将c除1000,不段重复这个步骤
- 输出时,若c为负数,则先输出负号;输出首个数字后,对于后面的数字,需要注意补充前导0,比如若为1,则补充为001
心得体会
这道题主要是注意特殊情况:1. 和为负数的情况 2. 补充前导0的情况 3. 使用栈时注意栈是否为空,避免段错误。
完整代码
#include<iostream>
#include<stack>
#include<cmath>
using namespace std;
int main()
{
//输入两个数
int a,b;
cin>>a>>b;
int c = a+b;
//保留符号位
int flg = c<0;
//取绝对值
c = abs(c);
stack<int>s;
//结果为0
if(c==0) {
cout<<"0";
return 0;
}
while(c) {
s.push(c%1000);
c /= 1000;
}
if(flg){
cout<<"-";
}
cout<<s.top();
s.pop();
while(s.size()!=0){
cout<<",";
int curr = s.top();
//补充前导0
if(curr>99) {
cout<<s.top();
} else {
if(curr>9) {
cout<<"0"<<curr;
} else {
cout<<"00"<<curr;
}
}
s.pop();
}
}