[PAT解题报告] Read Number in Chinese
不难,但很麻烦。用中文读一个数。
数不超过9位。
我是补足12位的,首位补0。
按照我们读数的方法,4位一级。
(xxxx)(yyyy)(zzzz)
xxxx是亿
yyyy是万
zzzz是个,不用读。
话虽如此,细节很多。
首先,读4位数,先写好,要注意
零什么时候读,什么时候不读,什么时候读一个……
只有第一次遇到0(前面非0),才读而且值读一个0。
读好4位数,我的算法是读3个4位数就好了。
但是仍然要注意0的问题。
全是0的时候,之前没读过东西就不读,否则要读一个0。
还有如果这个数< 1000,也就是不足4位,之前有东西的时候,还是要读一个0。
每读一个四位数加上一个单位,亿或者万,全0又不加……
细节规则,慢慢处理。
代码:
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const string number[] = {"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
const string weight[] = {"Qian","Bai","Shi",""};
const string we[] = {"Yi","Wan",""};
string readnumber(const char *s) {
int i;
for (i = 0; (i < 4) && (s[i] == '0'); ++i)
;
if (i >= 4) {
return number[0];
}
string answer = number[s[i] - '0'];
if (i < 3) {
answer += " " + weight[i];
}
bool mark = false;
for (++i; i < 4; ++i) {
if (s[i] == '0') {
mark = true;
}
else {
if (mark) {
answer += " " + number[0];
mark = false;
}
answer += " " + number[s[i] - '0'];
if (i < 3) {
answer += " " + weight[i];
}
}
}
return answer;
}
int main() {
char s[100];
bool sign = true;
scanf("%s",s);
string num;
if (s[0] == '-') {
sign = false;
num = s + 1;
}
else if (s[0] == '+') {
num = s + 1;
}
else {
num = s;
}
while (num.size() < 12) {
num = "0" + num;
}
bool mark = false;
string answer = "";
for (int i = 0, j = 0; i < 3; ++i) {
int x = (num[j] - '0') * 1000 + (num[j + 1] - '0') * 100 + (num[j + 2] - '0') * 10 + num[j + 3] - '0';
if (x == 0) {
if (!answer.empty()) {
mark = true;
}
}
else {
if ((!answer.empty()) && (mark || (x < 1000))) {
answer += " " + number[0];
mark = false;
}
if (!answer.empty()) {
answer += " ";
}
answer += readnumber(num.c_str() + j);
if (i < 2) {
answer += " " + we[i];
}
}
j += 4;
}
if (answer.empty()) {
puts(number[0].c_str());
}
else {
if (!sign) {
printf("Fu ");
}
puts(answer.c_str());
}
return 0;
}
原题链接: http://www.patest.cn/contests/pat-a-practise/1082
