1、题目:
模拟老式手机输入,九宫格布局如下:
题目输入为数字或者’-’,其中‘-’代表手机输入时等待的时间间隔,数字表示点击某
个按键的次数。比如点击两次 2,则输出为 B,四次 2,则输出为 A。
输入:
255
输出:
AK
输入(等待间隔‘-’可以无限长,也可以没有):
2222------55
输出:
AK
2、思路
- 对于不知道长度的字符串,最好定义为string类型,然后cin>>str
- cnt定义在循环内,既可以控制i的前进步伐,也可以统计重复字符数,很巧妙!!
#include<iostream>
#include<string>
using namespace std;
int main() {
string str;
char mp[10][4] = { {},{},{'A','B','C'},{'D','E','F'},{'G','H','I'},{'J','K','L'},{'M','N','O'},{'P','Q','R','S'},{'T','U','V'},{'W','X','Y','Z'} };
int i = 0;
cin >> str;
while (i < str.length()) {
int cnt=1;
int j = i;
while (str[j] == str[j + 1] && str[j] >= '0'&&str[j] <= '9') {
cnt++;
j++;
}
if (str[i] == '7' || str[i] == '9')
cout << mp[str[i] - '0'][(cnt - 1) % 4];
else if(str[i] >= '0'&&str[i] <= '9'&&str[i] != '7'&&str[i] != '9')
cout << mp[str[i] - '0'][(cnt - 1) % 3];
i += cnt;
}
system("pause");
return 0;
}