美文网首页
PAT1001 A+B Format (20 分)(字符串处理

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

作者: yestinl | 来源:发表于2018-10-30 19:23 被阅读0次

    题目

    image

    分析题目:

    两个数字相加,然后需要以一定格式输出。先求相加,然后把数字一个个对10取模输出,相对比较容易。用栈做一个后进后出就好了。

    代码:

    #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;
    }
    

    总结:

    做的时候没用对容器,从vector到queue最后才是stack,下次动手之前先分析好题目。

    pat1002

    题目

    image.png

    分析题目

    两个多项式相加,输出相应多项式项数和系数,用map即可完成对应

    代码(未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;
    }
    

    总结:

    重新熟练了map的插入、遍历操作,其中还用了一个对key值降序排列的重定义。注意题目对小数位的输出要求。但不知道为什么没有AC

    相关文章

      网友评论

          本文标题:PAT1001 A+B Format (20 分)(字符串处理

          本文链接:https://www.haomeiwen.com/subject/vhhntqtx.html