1001 A+B Format (20分)

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 −. 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
			
#include<iostream>
#include<string>
using namespace std;
int main()
{
    int a, b;
    cin >> a >> b;
    int ans = a + b;
    string s = to_string(ans);//字符串保存和,然后从尾开始遍历每3个在之前添加一个,号
    int len = s.size();
    int cnt;
    if (ans < 0)
    {
        cnt = 0;
        if (len >= 5)//当是-999时,长度为4,直接输出,不用添加
        {
            for (int i = len - 1; i >= 1; i--)//遍历到s[1]
            {
                cnt++;
                if (cnt == 3&&i!=1)
                {
                    s.insert(i, ",");//每3个在前面添加一个逗号
                    cnt = 0;//置0
                }
            }
        }
    }
    else
    {
        cnt = 0;
        if (len >= 4)//同理999就不用添加直接输出
        {
            for (int i = len - 1; i >= 0; i--)
            {
                cnt++;
                if (cnt == 3 && i != 0)
                {
                    s.insert(i, ",");
                    cnt = 0;
                }
            }
        }
    }
    cout << s << endl;
    return 0;
}
方法2:
#include <iostream>
using namespace std;
int main() {
    int a, b;
    cin >> a >> b;
    string s = to_string(a + b);
    int len = s.length();
    for (int i = 0; i < len; i++) {
        cout << s[i];
        if (s[i] == '-') continue;
        if ((i + 1) % 3 == len % 3 && i != len - 1) cout << ",";//每3位一插入,且是从尾往头插入,所以比如 2000000,len=7,7%3=1,所以是有一个1单独出来的,当s[i]=2时
//i=0,i+1=1;i+1%3=1,所以这里单了个1出来后,后面就要有个逗号,然后i=3时,i+1=4,即从头到这个位置有4个元素,前面1添加了逗号,这里4个元素后面也要添加逗号,再翻译下,两个逗号之间要有3个元素    }
    return 0;
}