1001 A+B Format (20 分)(字符串处理)

Description

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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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

生词

英文 解释
comma 逗号

题目大意:

计算A+B的和,然后以每三位加一个"."的格式输出~

分析:

把a+b的和转为字符串s~除了第一位是负号的情况,只要当前位的下标i满足(i + 1) % 3 == len % 3并且i不是最后一位,就在逐位输出的时候在该位输出后的后面加上一个逗号~

原文链接

题解

最后一个位置肯定不必输出逗号. 如果下标(从1算 故+1)和长度 整除以 3的余数相同,那么要输出一个逗号. 即 长度减去下标 如果 被3 整除,输出逗号, 最后一个位置除外.(参考某位评论区大佬解释)
其实就是这个字符串后半段对3取余

#include <bits/stdc++.h>

using namespace std;
/*
-99 999  6
-999 999 7
99 999   5
999 999  6
*/
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif
    int a,b;
    scanf("%d %d",&a,&b);
    string s=to_string(a+b);
    for(int i=0; i<s.length(); i++)
    {
        cout<<s[i];
        if(s[i]=='-') continue;
        if((s.length()-(i+1))%3==0&&i!=s.length()-1) cout<<",";
    }
}
posted @ 2021-11-04 14:57  勇往直前的力量  阅读(20)  评论(0编辑  收藏  举报