这个模拟题还是挺有意思的,大家做这种模拟题按照自己的逻辑模拟一遍,然后再把你模拟的过程用算法表示出来。虽然是这个道理,但是实际动手还是有考虑不周全的地方,慢慢学习改进吧。。。
难点主要是0的处理还有读Wan的情况。
这里提供几个测试点,测试点3好像就是全0, 测试点4是数字前面有无效的0。
-0000
-008
-10011000
10101008
#include<bits/stdc++.h>
using namespace std;
string mtc[4] = {"", " Shi", " Bai", " Qian"};
string num[10] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
vector<string> ans;
int main() {
//flag在遇0时置为1,且遇到下一个不为0的数时读出ling。
//flagw是标记在万位以上是否有不为0的数,有就要把Wan读出来
int flag = 0, flagw = 0;
string s;
cin >> s;
if (s[0] == '-') {
ans.push_back("Fu");
s = s.substr(1);
}
for (int i = 0; i < s.size(); i++) {
if (s[i] != '0') {
s = s.substr(i);
break;
}
}
if (s[0] == '0') {
if (ans.size() != 0) cout << ans[0] + " ling";
else cout << "ling";
return 0;
}
if (s.size() == 9) {
if (s[0] != '0') {
ans.push_back(num[s[0] - '0'] + " Yi");
}
s = s.substr(1);
}
if (s.size() > 4) {
string temp = s.substr(0, s.size() - 4);
for (int i = 0; i < temp.size(); i++) {
if (temp[i] == '0') flag = 1;
if (temp[i] != '0') {
if (flag == 1) {
ans.push_back("ling");
flag = 0;
}
flagw = 1;
ans.push_back(num[temp[i] - '0'] + mtc[temp.size() - i - 1]);
}
}
if (flagw) ans.push_back("Wan");
s = s.substr(s.size() - 4);
}
for (int i = 0; i < s.size(); i++) {
if (s[i] == '0') flag = 1;
if (s[i] != '0') {
if (flag == 1) {
ans.push_back("ling");
flag = 0;
}
flagw = 0;
ans.push_back(num[s[i] - '0'] + mtc[s.size() - i - 1]);
}
}
for (int i = 0; i < ans.size(); i++) {
// if (ans[i] == "Wan" && flagw == 1) continue;
if (i != 0) printf (" ");
cout << ans[i];
}
} #include<bits/stdc++.h>
using namespace std;
string mtc[4] = {"", " Shi", " Bai", " Qian"};
string num[10] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
vector<string> ans;
int main() {
int flag = 0, flagw = 0;
string s;
cin >> s;
if (s[0] == '-') {
ans.push_back("Fu");
s = s.substr(1);
}
for (int i = 0; i < s.size(); i++) {
if (s[i] != '0') {
s = s.substr(i);
break;
}
}
if (s[0] == '0') {
if (ans.size() != 0) cout << ans[0] + " ling";
else cout << "ling";
return 0;
}
if (s.size() == 9) {
if (s[0] != '0') {
ans.push_back(num[s[0] - '0'] + " Yi");
}
s = s.substr(1);
}
if (s.size() > 4) {
string temp = s.substr(0, s.size() - 4);
for (int i = 0; i < temp.size(); i++) {
if (temp[i] == '0') flag = 1;
if (temp[i] != '0') {
if (flag == 1) {
ans.push_back("ling");
flag = 0;
}
flagw = 1;
ans.push_back(num[temp[i] - '0'] + mtc[temp.size() - i - 1]);
}
}
if (flagw) ans.push_back("Wan");
s = s.substr(s.size() - 4);
}
for (int i = 0; i < s.size(); i++) {
if (s[i] == '0') flag = 1;
if (s[i] != '0') {
if (flag == 1) {
ans.push_back("ling");
flag = 0;
}
flagw = 0;
ans.push_back(num[s[i] - '0'] + mtc[s.size() - i - 1]);
}
}
for (int i = 0; i < ans.size(); i++) {
// if (ans[i] == "Wan" && flagw == 1) continue;
if (i != 0) printf (" ");
cout << ans[i];
}
}