PAT:1001 A+B Format (20分)

任老爸張發表於2020-10-03

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

看範圍發現,int型是完全ok的,所以用int就行了,相加後再轉為string,來分析什麼時候加逗號,將string與3取餘,將其分成3的段,那麼最前面剩下的就是不夠的,每當i=餘數時,先輸出,號,之後就是每過3個輸出一個逗號,相當於於3取餘後仍是之前的數。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int a,b;
    cin>>a>>b;
    string c=to_string(a+b);
    for(int i=0;i<c.length();i++){
        cout<<c[i];
        if(c[i]=='-') continue;
        if(c.length()%3==(i+1)%3&&i!=c.length()-1) cout<<",";
    }
}

相關文章