题目链接
题目详情
一时间网上一片求救声,急问这个怎么破。其实这段代码很简单,index数组就是arr数组的下标,index[0]=2 对应 arr[2]=1,index[1]=0 对应 arr[0]=8,index[2]=3 对应 arr[3]=0,以此类推…… 很容易得到电话号码是18013820100。
本题要求你编写一个程序,为任何一个电话号码生成这段代码 —— 事实上,只要生成最前面两行就可以了,后面内容是不变的。
输入格式:
输入在一行中给出一个由11位数字组成的手机号码。
输出格式:
为输入的号码生成代码的前两行,其中arr中的数字必须按递减顺序给出。
输入样例:
18013820100
输出样例:
int[] arr = new int[]{8,3,2,1,0};
int[] index = new int[]{3,0,4,3,1,0,2,4,3,4,4};
解题思路
这题很有意思,(PTA常常结合微博热点出题),给我们一个手机号,让我们实现图片中前两行代码。
第一行代码记录那些数字出现过,字符串在进行操作时,若要对其中的某一字符转换成数字则s[i]-'0'。
int a[15];//记录哪些数出现过
for (int i = 0; i < 11; i++)
{
int x = s[i] - '0';
a[x] = 1;
}
然后cnt同时记录a1[]的下标和号码个数,因为我们要对出现的数字进行降序排序。
接下来是第二行,只需枚举号码数组和出现数组,并比较即可判断号码中每个数字出现的位置。
for (int i = 0; i < 11; i++)
{
for (int j = 0; j < cnt; j++)
{
if (s[i]-'0' == a1[j])
{
cout << j;
if (i != 10) cout << ",";
}
}
}
AC代码
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int x, int y) {
return x > y;
}
int main()
{
string s;
cin >> s;
int a[15];//记录哪些数出现过
for (int i = 0; i < 11; i++)
{
int x = s[i] - '0';
a[x] = 1;
}
int a1[15]; int cnt = 0;
for (int i = 0; i <= 9; i++)
{
if (a[i] == 1)
{
a1[cnt++] = i;
}
}
sort(a1, a1 + cnt,cmp);
cout << "int[] arr = new int[]{";
for (int i = 0; i < cnt; i++)
{
cout << a1[i];
if (i != cnt - 1) cout << ",";
}
cout << "};" << endl;
//第二行
cout << "int[] index = new int[]{";
for (int i = 0; i < 11; i++)
{
for (int j = 0; j < cnt; j++)
{
if (s[i]-'0' == a1[j])
{
cout << j;
if (i != 10) cout << ",";
}
}
}
cout << "};" << endl;
return 0;
}