pat练手


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 −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


/*
题目思路:a,b范围在int内,不用大数操作。
用stringstream从int转化成string
有负数先输出负数, 然后len<4,直接输出。
否则k=len%3 
先输出前面不够三个的,处理一下,后面则是3的倍数。

坑点:,是从右向前数3个
*/

代码


#include<bits/stdc++.h>
using namespace std;
int a, b;
int main() {
    cin >> a >> b;
    int c = a+b;
    if(c<0){
        cout <<"-";
        c = -c;
    }
    string str;
    stringstream ss;
    ss << c;
    ss >> str;
    int len = str.length();
    if(len < 4){
        cout << str << endl;
        return 0;
    }
    int k = len % 3;
    for(int i=1; i<=k; i++){
        cout << str[i-1];
        if(i==k)
            cout <<",";
    }
    len -= k;
    for(int i=1; i<=len; i++){
        cout << str[i+k-1];
        if(i%3==0 && i!=len)
            cout <<",";
    }
    return 0;
}

全部评论

相关推荐

一颗宏心:华为HR晚上过了十二点后还给我法消息。
点赞 评论 收藏
分享
Noob1024:一笔传三代,人走笔还在
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务