PAT1001 A+B Format (20 分)(字符串處理)

題目

image

分析題目:

兩個(gè)數(shù)字相加,然后需要以一定格式輸出。先求相加,然后把數(shù)字一個(gè)個(gè)對(duì)10取模輸出,相對(duì)比較容易。用棧做一個(gè)后進(jìn)后出就好了。

代碼:

#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
stack<char> sta;
int main()
{
    int a, b;
    cin >> a >> b;
    int result;
    result = a + b;
    int n = abs(result);
    int flag = -1;
    while(n)
    {
        int c = 0;
        c = n%10;
        flag++;
        n /= 10;
//        cout << n << " " << flag << endl;
        if(flag == 3)
        {

            int sign = ',';
            sta.push(sign);
            flag = 0;
        }
        sta.push(c+'0');
    }
    if(result<0)
        cout << "-";
    if(result == 0)
        cout << "0";
    while(!sta.empty())
    {
        char d = sta.top();
        cout << d;
        sta.pop();
    }
    cout << endl;
    return 0;
}

總結(jié):

做的時(shí)候沒(méi)用對(duì)容器,從vector到queue最后才是stack,下次動(dòng)手之前先分析好題目。

pat1002

題目

image.png

分析題目

兩個(gè)多項(xiàng)式相加,輸出相應(yīng)多項(xiàng)式項(xiàng)數(shù)和系數(shù),用map即可完成對(duì)應(yīng)

代碼(未AC)

#include <iostream>
#include <map>
#include <cstdio>
using namespace std;
map<int,double, greater<int> > vec;
int main()
{
    int k1;
    cin >> k1;
    while(k1--)
    {
        int N;
        double a;
        cin >> N >> a;
        vec[N] = a;
    }
    int k2;
    cin >> k2;
    while(k2--)
    {
        int N;
        double a;
        cin >> N >> a;
        map<int, double>::iterator it;
        it = vec.find(N);
        if(it == vec.end())
            vec[N] = a;
        else
            vec[N] += a;
    }
    cout << vec.size();

    for(map<int, double>::iterator it = vec.begin(); it != vec.end(); it++)
        printf(" %d %.1lf", it->first, it->second);
    cout << endl;
    return 0;
}

總結(jié):

重新熟練了map的插入、遍歷操作,其中還用了一個(gè)對(duì)key值降序排列的重定義。注意題目對(duì)小數(shù)位的輸出要求。但不知道為什么沒(méi)有AC

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容