1001. A+B Format (20)

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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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 <vector>
#include <iostream>

using namespace std;
int abs(int num){   //c++中的基本函数还是可以用的    
    return (num >= 0) ? num : (-num);
}
vector<char>  breakFunc(int input){

    vector<char> res;   //用向量,是个不明智之举,很明显这是一个先入后出的数据模型,因此需要用到栈
    int temp = abs(input);
    int flag=0;
    while (temp / 10 > 0){
        flag++;     
        res.push_back((char)(temp % 10) + '0');
        if ((flag % 3)== 0) //由于考虑不周全,这里最开始用的是 flag%3==0;然后改成了flag%3==0 || flag%6==0;还是不能全对
        {
            res.push_back('\,');    //这里转义字符要用\,
        }
        temp /= 10;     //一度纠结flag++及前三个代码段的位置,完全是通过debug凑出来的,由此可见,提前思考清楚代码算法的逻辑是多重要

    }
    res.push_back((char)temp + '0');    //拉过这一步,总是少一个数字。
    return res;
}
int main(){
    int a, b,c;
    while (cin >> a >> b){  //固定输入格式,关键:下面的这些代码块要放到循环语句中,而不是外面      
        c = a + b; 
        vector<char> res = breakFunc(c);
        if (a >= 0) //未考虑a=0的情况
        {
            for (int i = res.size() - 1; i >= 0; i--)   //vector逆向输出的方法,注意i>=0(i>0会拉掉一位数字)及i = res.size() - 1(i=res.size()会导致数组越界)
            {
                cout << res[i];
            }
        }
        else
        {
            cout << "-";
            for (int i = res.size() - 1; i >= 0; i--)
            {
                cout << res[i];
            }
        }
    }
    return 0;
}
这道题是PAT做的第一题,值得纪念,虽然断断续续花了将近2个小时,中间受过打击,想放弃,但好在最后坚持下来了。收获的是满满的成就感和坚持下去的冲动。
以前写代码都是看的别人的程序照葫芦画的,这次是第一次自己思考完成。中间int转char参考了网上的资源,说明c++一些基本的语法库还要完善学习
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值