一道面试题大家看看怎么做
对于一段形如:1 , -1~3 , 1~15x3 的输入,
输入会依据以下规则:
a、所有输入为整数;
b、“,”为分隔符;
c、“~”表示一个区间,比如“-1~3”表示-1到3总共5个整数,同时“~”前的数小于“~”后的数;
d、“x”表示步长,“x3”指每3个整数取一个,比如“1~15x3”表示1,4,7,10,13;
根据以上得到的结果进行打印,打印的规则为:
a、所有得到的整数按从小到大排列,以“,”分隔,不计重复;
b、每行最多显示3个整数;
c、如果两个整数是连续的,可以放在同一行,否则自动换行。
例如对于输入“1 , -1~3 , 1~15x3”的输出结果为:
-1,0,1,
2,3,4,
7,
10,
13
[解决办法]
int main(int argc, _TCHAR* argv[]){ char *str = (char *)calloc(100,sizeof(char)); //int *num = (int *)malloc(100*sizeof(int)); vector<int> num; while (1) { num.clear(); printf("请输入一组数字:\n"); //memset(str,0,100); scanf("%s",str); if (strlen(str)+1 > 100) { printf("输入数据量过大,请重新输入:\n"); continue; } char *strtemp[100]; for (int ii = 0 ; ii < 100 ; ii++) { strtemp[ii] = NULL; } //分解输入的字符串。 char *NextCommaTemp = NULL; char *CommaTemp = strtok_s(str,",",&NextCommaTemp); for (int i = 0;CommaTemp != NULL;i++) { strtemp[i] = CommaTemp; CommaTemp = strtok_s(NULL,",",&NextCommaTemp); } for (int j = 0;j < 100 ;j++) { if(strtemp[j] == NULL) break; //char *temp_1 = (char *)malloc(strlen(strtemp[j]+1)); char temp_1[100]; strcpy(temp_1,strtemp[j]); char *NextInterzoneTemp = NULL; char *InterzoneTemp = strtok_s(strtemp[j],"~",&NextInterzoneTemp); //if (InterzoneTemp == NULL) if (strcmp(InterzoneTemp,temp_1) == 0) { num.push_back(atoi(strtemp[j])); } else { //temp[2]中,0为“~”的前数,1为后数 //strMultiple[2]为“~”后数的分解,“x”前数为操作数,后数为步长。 char *temp[2],*strMultiple[2]; int multiple = 0; for (int k = 0;InterzoneTemp != NULL;k++) { temp[k] = InterzoneTemp; InterzoneTemp = strtok_s(NULL,"~",&NextInterzoneTemp); } char *temp_2 = (char*)malloc(strlen(temp[1])+1); strcpy(temp_2,temp[1]); char *NextMultipleTemp = NULL; char *multipleTemp = strtok_s(temp[1],"x",&NextMultipleTemp); if(strcmp(multipleTemp,temp_2) != 0) { for (int z = 0;multipleTemp != NULL;z++) { strMultiple[z] = multipleTemp; multipleTemp = strtok_s(NULL,"x",&NextMultipleTemp); } int temp1,temp2; temp1 = atoi(temp[0]); temp2 = atoi(strMultiple[0]); if (temp1 >= temp2) { printf("输入范围时前数不能大于等于后数,请重新输入:\n"); break; } else { int temp3 = atoi(strMultiple[1]); for (;temp1 < temp2 && temp1 != temp2;) { num.push_back(temp1); temp1 = temp1 + temp3; } } } else { int temp1,temp2; temp1 = atoi(temp[0]); temp2 = atoi(temp[1]); if (temp1 >= temp2) { printf("输入范围时前数不能大于等于后数,请重新输入:\n"); break; } else { for (;temp1 != temp2;temp1++) { num.push_back(temp1); } } } free(temp_2); } //free(temp_1); } vector<int>::iterator iter = num.begin(); for ( ; iter != num.end() ; iter++) { printf("%d\n",*iter); } } //free(num); free(str); //num = NULL; str = NULL; system("pause"); return 0;}