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,计算并输出两者的和,输出格式为从低到高为,每三位输出一个逗号(commas),如果位数为3的倍数或者位数小于等于3,那么就不用输出最高位后输出逗号。
思路分析:
定义整型变量a,b,c,接着利用整型数组s[8]保存a加b之和c的各位,然后设置一个工作变量i,从高位开始输出数组s[8],先输出s[i],若i%3==0,则输出','(不妨考虑结果c不止三位,在输出s[3]后,根据要求此时得输出一个逗号,对于6,9,...,3i,...同理,注意i==0时不用再输出逗号,因此我们可以将i不为0作为循环条件),最后单独输出s[0]。
参考代码:
#include <iostream>
using namespace std;
int main()
{
int a,b,c;
int s[8];
int i=0;
cin>>a>>b;
c=a+b;
if(c<0){
cout<<'-';
c=-c;
}
while(c){
s[i++]=c%10;
c/=10;
}
i-=1;
while(i){
cout<<s[i];
if(i%3==0){
cout<<',';
}
i-=1;
}
cout<<s[0]<<endl;
}
此时,出现段错误(数组越界或者堆栈溢出),开始的我,改了很多地方QAQ,,,不太懂哪里出现问题,最后想了一下,若果在i到第二个while判断之前,已为-1,此时将出现死循环,根据这一点推出若a+b的结果c为0,则直接输出0即可,否则按照之前的思路处理,改过之后的代码如下:
#include <iostream>
using namespace std;
int main()
{
int a,b,c;
int s[8];
int i=0;
cin>>a>>b;
c=a+b;
if(c<0){
cout<<'-';
c=-c;
}
while(c){
s[i++]=c%10;
c/=10;
}
if(i){
i-=1;
while(i){
cout<<s[i];
if(i%3==0){
cout<<',';
}
i-=1;
}
cout<<s[0]<<endl;
}else{
cout<<'0';
}
}
最后,贴一张通过堆栈得到的实现代码。思路是将结果按字符处理,压入堆栈中,且每压入三个字符,额外压入一个逗号,最后再将堆栈输出即可。
#include<cstdio>
#include<stack>
using namespace std;
int main(){
int a,b,c;
scanf("%d%d",&a,&b);
c=a+b;
if(c<0){
printf("-");
c=-c;
}
int k=0;
stack<char> q;
while(c/10){
q.push(c%10+'0');
k++;
c/=10;
if(k%3==0){
q.push(',');
}
}
q.push(c+'0');
int len=q.size();
for(k=0;k<len;k++){
printf("%c",q.top());
q.pop();
}
return 0;
}