题解
【基础】念数字
1 条题解
-
0
解题思路
题目要求把 0~99 之间的数用汉语拼音读出来,比如 35 读作 san shi wu,16 读作 shi liu,0 读作 ling。
先想清楚读法规则:
- 0~9:直接读个位拼音,比如 5 读 wu
- 10~19:读作 shi 开头,但前面不加 yi。比如 16 读 shi liu(不是 yi shi liu)
- 20~99:先读十位,再说 shi,再读个位。比如 35 读 san shi wu;整十数只到十位,如 20 读 er shi
怎么实现?
- 写一个函数 num(n),负责输出 0~9 的拼音
- 用除法和取余把数的十位和个位拆开:a = n 整除 10,b = n 对 10 取余
- 分情况讨论:
- 十位为 0:一位数,直接 num(b)
- 十位为 1:10~19,输出 shi(+ 个位)
- 十位大于 1:先 num(a),再输出 shi(+ 个位)
为什么要特别处理十位是 1? 因为汉语里 11~19 读作十一、十六,十位 1 不用读成 yi shi,所以十位是 1 时直接输出 shi。
参考代码
#include <iostream> using namespace std; void num(int n) { if (n == 1) cout << "yi"; else if (n == 2) cout << "er"; else if (n == 3) cout << "san"; else if (n == 4) cout << "si"; else if (n == 5) cout << "wu"; else if (n == 6) cout << "liu"; else if (n == 7) cout << "qi"; else if (n == 8) cout << "ba"; else if (n == 9) cout << "jiu"; else if (n == 0) cout << "ling"; } int main() { int n, a, b; cin >> n; a = n / 10; // 十位 b = n % 10; // 个位 if (a == 0) { num(b); // 一位数直接读个位 } else { if (a == 1) { // 10~19,读作 shi 开头 if (b == 0) cout << "shi"; else { cout << "shi "; num(b); } } else { // 20~99,先读十位再读 shi if (b == 0) { num(a); cout << " shi"; } else { num(a); cout << " shi "; num(b); } } } return 0; }复杂度分析
- 时间复杂度:O(1),只处理一个数
- 空间复杂度:O(1)
- 1