华为机试题

来源:互联网 发布:excel 去掉空格数据 编辑:程序博客网 时间:2024/06/06 03:14

输入一行数字: 123 423 5645 875 186523

再输入第二行: 23

将第一行中含有第二行中“23”的数排序并输出

结果即: 123 423 186523


解法1:

#include <stdio.h>#include <algorithm>using namespace std;int main() {    int a[20], ans[20], index = 0, index2 = 0, m, x;    char c = '0';    while(c != '\n') {        scanf("%d%c", &a[index++], &c);    }    scanf("%d", &m);    for(int i  = 0; i < index; i++) {        if(a[i] > 0) {            if(a[i]%100 == m)                ans[index2++] = a[i];            else                a[i] /= 10;        }    }    sort(ans, ans+index2);    for(int i = 0; i < index2-1; i++)        printf("%d ", ans[i]);    printf("%d\n", ans[index2-1]);    return 0;}


解法2:

#include <iostream>#include <string>#include <vector>#include <sstream>#include <algorithm>using namespace std;int main() {    stringstream ss,ss2;    string words, word, key;    int x;    vector<int> ivec;    getline(cin, words);    cin >> key;    ss << words;    while(!ss.eof()) {        ss >> word;        if(word.find(key) != string::npos) {            ss2 << word;            ss2 >> x;            ss2.str("");            ss2.clear();            ivec.push_back(x);        }    }    sort(ivec.begin(), ivec.end());    bool flag = true;    for(vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter) {        if(flag) {            cout << *iter;            flag = false;        }        else {            cout << " " << *iter;        }    }    cout << endl;    return 0;}



0 0
原创粉丝点击