携程旅行2019年春招-研发方向B-编程第二题

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

给定一列数,指定分组大小,组内交换位置;剩余构不成分组的数,位置保持不变

eg:[1,2,3,4,5]

2

输出:[2,1,4,3,5]

eg:[1,2,3,4,5]

3

输出:[3,2,1,4,5]

我忘了截图,大致就这个意思;

代码当时没写完,笔试结束后写完的,我觉得大概可能也会没问题吧~

#include <iostream>
#include <string.h>
using namespace std;
const int N=1003;

int main(){
	ios::sync_with_stdio(false);
	
	char str[N],tmp[N];
	int i,j,t,k,l;
	cin>>str;
	cin>>k;
	
	t=1;
	tmp[0]=str[0];
	for(i=2*k-1;i<strlen(str);i+=(2*k)){//每个循环的起点 
		l=(i-2*k);
		if(l<0){
			l=0;
			for(j=i;j>l;j--){
				tmp[t]=str[j];
				t++;
			}
			tmp[t]=',';
			t++;
			continue;			
		}
			
		for(j=i;j>l;j--){
			tmp[t]=str[j];
			t++;
		}

	}

	if(i-2*k+2==strlen(str)){
		tmp[t-1]=']';		
	}else{
		for(i=i-(2*k)+2;i<strlen(str);i++){
			tmp[t]=str[i];
			t++;
		}	
	}
	
	for(i=0;i<t;i++){
		cout<<tmp[i];
	}
	cout<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Lydia_r/article/details/89108840