牛客练习赛67 A、B题解

A

Description

牛牛得到了一个字符串(可能含有空格),他希望在这些字符串中提取出数字。
例如:a1b23c456d007890中可以提取出1, 23, 456, 7890共4个数字。

现在,他得到了一个长度高达1000的字符串,请你帮他提取出所有的数字。

Input

本题有多组数据。
输入一个字符串S。

Output

输出提取出的所有数字,相邻两个数字用一个空格隔开。
不包含数字的时候输出空行
注意,你输出的数不能含有前导0。

Solution

利用一个栈来维护,遍历字符串,遇到一个数字,若栈空,将其入栈,否则判断一下,栈是否只有一个元素并且为字符’0’,是,将其出栈,然后将当前字符入栈。遇到非数字字符,判断栈是否为空,不为空,将栈内元素全部出栈,翻转一下,输出。

AC Code
#include<iostream>
#include<string>
#include<stack>
#include<algorithm>
using namespace std;
int main() {
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    string s;
    while (getline(cin, s)) {
        int flag = 0;
        int qian0 = 0;
        stack<char> t;
        for (int i = 0; i < s.length(); i++) {
            if ('0' <= s[i] && s[i] <= '9') {
                if ( t.size() == 1 && t.top() == '0') {
                    t.pop();
                    t.push(s[i]);
                }
                else t.push(s[i]);
            }
            else {
                if (!t.empty()) {
                    string ans;
                    while (!t.empty()) {
                        ans += t.top();
                        t.pop();
                    }
                    for (int i = ans.length() - 1; i >= 0; i--) cout << ans[i];
                    cout << " ";
                }
            }
        }
        if (!t.empty()) {
            string ans;
            while (!t.empty()) {
                ans += t.top();
                t.pop();
            }
            for (int i = ans.length() - 1; i >= 0; i--) cout << ans[i];
            cout << " ";
        }
        cout<<endl;
    }
}

B

Description

水题,白给!

Solution

一个数与另一个数进行&运算,不会变得比原来大,所以直接输出最大值!

AC Code
#include<bits/stdc++.h>
using namespace std;
int main(){
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        int m=0;
        while(n--){
            int x;
            cin>>x;
            if(x>m) m=x;
        }
        cout<<m<<endl;
    }
    return 0;
}

觉得有帮助的话,点个赞再走吧!

猜你喜欢

转载自blog.csdn.net/buibuilili/article/details/108014604