PAT甲级1001

219 阅读1分钟

题目

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).

输入格式

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.

输出格式

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.

翻译

简略的翻译为计算A+B的和,然后以每三位加⼀个”,”的格式输出.

思路

看着好像很简单,我也非常轻松的写出了首版代码,非常快的,就是部分正确:

//foreverking
#include <vector>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
#include <stack>
using namespace std;

int a, b, cnt;
string s;

int main() {
    cin >> a >> b;
    int c = a + b;
    if(c < 0){
        cout << '-';
        c = abs(c);//绝对值
    }
    s = to_string(c);//转化为string s
    int len = s.size();
    for(int i = 0; i < len; i++){
        cout << s[i];
        cnt++;
        if(cnt == 3 && (i + 1) != len && i != len){
            cout << ',';
            cnt = 0;
        }
    }
    cout << endl;
    return 0;
}

区分正负,负数先输出'-'.正数不做处理。而后转化为string,每隔三个字符就输出一个','。注意如果是最后一个字符,不输出。让人悲伤的是,他错了,看了一下午,原来他是从后往前数三个添一个',',那么思路就要转化了。

既然开头的负号,结尾是否输出','都让人为难,而且你知道','是从后找,那就倒着处理字符串。那么你看,先进后出,这不就是栈嘛,基本思路还是一样的,只是用栈去实现。

//foreverking
#include <vector>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
#include <stack>
using namespace std;
//栈,从尾部处理,再从头部出栈
int a, b, cnt = 0;

int main() {
    int result;
    stack<char> outcome;
    cin >> a >> b;
    result = a + b;
    int c = abs(result);
    while (c > 0) {
        outcome.push('0' + c % 10);//进栈,转为char
        c /= 10;
        cnt++;//计数器,满三归零
        if (cnt == 3 && c > 0) {
            outcome.push(',');
            cnt = 0;//归零
        }
    }
    
    if(result < 0)
        cout << '-';
    else if (result == 0)
        cout << '0';
        
    while (!outcome.empty()) {
        cout << outcome.top();//输出
        outcome.pop();//出栈
    }
    cout << endl;
    return 0;
}

其实你也可以reevrse这个string再处理,或者直接从尾巴往头数,不过用栈绝对是个好主意。

题目链接