PAT —— 1001 A+B Format(C / C++)

题目​​​​​​​

1001 A+B Format (pintia.cn)


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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值