编程题
程序员文章站
2022-07-15 21:04:40
...
题目摘自网友发的2018阿里巴巴在线编程题
输入数据n(n>=6)代表n个数,从0-9任意输入n个数,然后在n个数选出6个数xx-xx-xx表示 时:分:秒,求出最小时间和最大时间,若时间无效,则输出时间无效
例如: 输入: 6 6 5 4 3 2 1
输出: 123456 235641
输入: 6 9 9 9 9 9 9 输出: 时间无效
结题思路
因为输入数字限定为0-9,记录每个数字的输入次数,根据需求取出最大或者最小的数,每取出一个数,对应数字的出现次数减1
main函数
int main(int argc, char *argv[])
{
int num;
cin >> num;
if (num < 6)
{
cout << "Input num must be greater than 6" << endl;
system("pause");
return 0;
}
int data[10] = { 0 };
int data2[10] = { 0 };
int tmp;
for (int i = 0; i < num; i++)
{
cin >> tmp;
data[tmp]++;
}
memcpy(data2, data, 10 * sizeof(int));
cout << "min time is:";
int ret = 1;
ret &= output(data, 0, 2);
ret &= output(data, 0, 3);
ret &= output(data, 0, 5);
ret &= output(data, 0, 9);
ret &= output(data, 0, 5);
ret &= output(data, 0, 9);
if (ret == 0)
{
cout << endl << "invalid input" << endl;
system("pause");
return -1;
}
// max time
cout << "max time is:";
ret = 1;
ret &= output(data2, 2, 0);
ret &= output(data2, 3, 0);
ret &= output(data2, 5, 0);
ret &= output(data2, 9, 0);
ret &= output(data2, 5, 0);
ret &= output(data2, 9, 0);
if (ret == 0)
{
cout << endl << "invalid input" << endl;
system("pause");
return -1;
}
cout << endl;
system("pause");
}
输出函数
int output(int* pVal, int start, int end)
{
if (start <= end)
{
for (int i = start; i <= end; i++)
{
if (pVal[i] > 0)
{
cout << i;
pVal[i]--;
return 1;
}
}
}
else
{
for (int i = start; i >= end; i--)
{
if (pVal[i] > 0)
{
cout << i;
pVal[i]--;
return 1;
}
}
}
return 0;
}