首页 > 其他 > 详细

PAT 甲级 1001 A+B Format

时间:2021-02-08 10:39:32      阅读:37      评论:0      收藏:0      [点我收藏+]

地址   https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400

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≤106 ?? . 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

题目大意是 

两数相加 使用每个三个数字打印一个‘,‘的形式将其显示出来

解答

这个主要是熟悉 字符串与数字之间的转换逆转换。

模拟题,主要注意数字和字符串的转换,并且每隔三个数字就要加上一个逗号
但是逗号任意一边只有负号或者是起点 或终点则不必添加逗号(-199 199 )

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int n, m;

int main()
{
    cin >> n >> m;
    int k = n + m;
    string ans;
    int flag = 0;
    if (k < 0) {flag = 1;k = abs(k);}
    else if (k == 0) {cout << 0 << endl;return 0;}

    int count = 0;
    while (k != 0) {
        int tmp = k % 10;k = k / 10;
        ans += (char)(0 + tmp);
        count++;
        if (count % 3 == 0 && k!=0) {ans += ,;}
    }
    reverse(ans.begin(),ans.end());
    if (flag) ans.insert(ans.begin(), -);

    cout << ans << endl;
    return 0;
}

 

 

PAT 甲级 1001 A+B Format

原文:https://www.cnblogs.com/itdef/p/14387174.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!