欢聚时代(YY)2019校招-推荐系统开发(C++)A卷编程题解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jirryzhang/article/details/82706861

据说都是剑指offer原题,但没用剑指offer的方法写(因为没怎么背答案)。

1、特定字符替换为20%

因为输入没有限制为char数组,也没说不能开新数组,所以没有在原有内存空间替换,用string遍历一把做替换,生成一个新的string.

#include<iostream>
#include<string>
using namespace std;

string solve(const string &str)
{
    int len=str.size();
    string res="";
    for(auto i=0;i<len;++i){
        if(str[i]=='#')
            res += "%20";
        else
            res.push_back(str[i]);
    }
    return res;
}

int main()
{
    string str;
    while(cin>>str)
        cout<<solve(str)<<endl;
    return 0;
}

2、排序数组,奇数在前半部分,按升序排,偶数在后半部分,按降序排

直接stl sort函数过了。输入比较坑。

#include<iostream>
#include <vector>
#include <algorithm>
using namespace std;
int cmp(const int&a,const int &b){
    if((a%2)!=0){
	    if(b%2==0)
		    return true;
	    else
		    return a<b;
    }else{
	    if(b%2!=0)
		    return false;
	    else
		    return a>b;
	}
}
int main()
{
	vector<int> v;
	int n;
	char c;  
	while((c=getchar())&&(c==' '||(c<='9'&&c>='0')))  
	{  
		ungetc(c,stdin);  
		cin>>n; 
		v.push_back(n);
	}  
	sort(v.begin(),v.end(),cmp);
	for(int i=0;i<v.size()-1;++i){
		cout<<v[i]<<" ";
	}
	cout<<v[v.size()-1]<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/jirryzhang/article/details/82706861
今日推荐