当前位置: 代码迷 >> 综合 >> PTA-A:1001 A+B Format (20分)
  详细解决方案

PTA-A:1001 A+B Format (20分)

热度:111   发布时间:2023-10-13 13:42:58.0

题解目录

    • 1001 A+B Format (20分)
    • Input Specification:
    • Output Specification:
    • Sample Input:
    • Sample Output:
    • Submit

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 ?10e?6≤a,b≤10e6. 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

Submit

#include<iostream>using namespace std;int main(){
    int a, b, sum=0;cin>>a>>b;sum=a+b;if(sum/int(1e6))   printf("%d,%03d,%03d\n", sum/int(1e6), abs(sum%int(1e6)/int(1e3)), abs(sum%int(1e3)));else if(sum/int(1e3))  printf("%d,%03d\n", sum/int(1e3), abs(sum%int(1e3)));else printf("%d\n", sum%int(1e3));return 0;
}
#include<iostream>
#include<string>
#include<algorithm>using namespace std;int main(){
    int a,b,sum;scanf("%d %d", &a, &b);sum = a + b;string s1 = to_string(sum);string s2 = "";for(int i = s1.length() - 1, tep = 1; i >= 0; i--, tep++){
    s2 += s1[i];if(tep && tep % 3 == 0 && i-1 >= 0 && s1[i-1] != '-')  s2 += ','; }reverse(s2.begin(), s2.end());printf("%s\n", s2.c_str());return 0;
}
  相关解决方案