现在的位置: 首页 > 综合 > 正文

华为机试题

2017年11月17日 ⁄ 综合 ⁄ 共 963字 ⁄ 字号 评论关闭

输入一行数字: 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;
}

抱歉!评论已关闭.