题目
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 −10^6 ≤ a,b ≤ 10^6. 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
限制:
代码长度限制 16 KB
时间限制 400 ms
内存限制 64 MB
题目大意
简单的加法运算+格式化输出,自右向左没三个一组以 ‘ ,‘ 分开
思路一(精简版 - C++):
首先将 a 和 b 的和用 s 储存起来,输出时需注意 , 的位置。
1、 ,不可以出现在 - 后面和末尾;
2、 , 从右向左每三个一组进行分割,少于三个的不加;
以下是代码段:(4ms)
#include<iostream>
using namespace std;
int main()
{
int a,b,i;
cin >> a >> b;
string s = to_string(a+b);//转化字符串函数,适用VScode
int len = s.length();
for(i = 0;i < len;i++)
{
cout << s[i];
if (s[i] == '-') continue;
if(i % 3==((len-1) % 3) && i != len-1)
cout << ',';
}
}
思路二(转化成字符数组 - C):
灵活运用函数迭代,可以避免使用数组,且速度更快,注意细节同上。
以下是代码段(2ms):
#include<stdio.h>
void cag(int s,int c);
int main()
{
int a,b,s;
scanf("%d%d",&a,&b);
s=a+b;
if(s==0)printf("0");
else if(s>0) cag(s,0);
else {
printf("-");
s*=-1;
cag(s,0);
}
}
void cag(int s,int c)
{
if(s==0)return ;
cag(s/10,++c);
if(c%3==0 && s>=10)printf(",");//s >= 10 防止 , 出现在 - 后面
printf("%d",s%10);
}
思路三(运用数组 - C) :
思路相似,格式问题注意一下
以下是代码段(2ms):
#include <stdio.h>
int main() {
int a, b, s, k = 0, symbol = 1;
int group[3];
scanf("%d%d",&a,&b);
s = a + b;
if(s < 0){
s = -s;
symbol = -1;
}
do{
group[k++] = s % 1000;
s /= 1000;
}while (s);
if(symbol == -1)printf("%c", '-');
printf("%d", group[--k]);
while (k > 0) {
printf(",%03d", group[--k]);
}
return 0;
}