【PAT】 1002 写出这个数 Rust Solution

读入一个正整数 n,计算其各位数字之和,用汉语拼音写出和的每一位数字。

输入格式:

每个测试输入包含 1 个测试用例,即给出自然数 n 的值。这里保证 n 小于 10100​​。

输出格式:

在一行内输出 n 的各位数字之和的每一位,拼音数字间有 1 空格,但一行中最后一个拼音数字后没有空格。

输入样例:

1234567890987654321123456789
 

输出样例:

yi san wu


 1 use std::collections::HashMap;
 2 use std::io;
 3 
 4 pub fn  write_the_number(n: String) -> Vec<String> {
 5 
 6     let mut  temp_hashmap = HashMap::new();
 7     temp_hashmap.insert(0u8, "ling");
 8     temp_hashmap.insert(1,"yi");
 9     temp_hashmap.insert(2, "er");
10     temp_hashmap.insert(3, "san");
11     temp_hashmap.insert(4, "si");
12     temp_hashmap.insert(5, "wu");
13     temp_hashmap.insert(6, "liu");
14     temp_hashmap.insert(7, "qi");
15     temp_hashmap.insert(8, "ba");
16     temp_hashmap.insert(9, "jiu");
17 
18 
19     let sum = n
20         .chars()
21         .map(|temp| {
22         temp.to_string()
23             .as_str()
24             .parse::<u32>()
25             .unwrap()
26         })
27         .collect::<Vec<u32>>()
28         .iter()
29         .sum::<u32>();
30 
31     let ret = sum
32         .to_string()
33         .chars()
34         .map(|i| {
35             let index = i.to_string().parse::<u8>().unwrap();
36             temp_hashmap.get(&index)
37                 .unwrap()
38                 .to_string()
39         }).collect::<Vec<String>>();
40 
41     ret
42 }
43 
44 
45 fn main() {
46     let mut input_string = String::new();
47 
48     io::stdin().read_line(&mut input_string)
49         .expect("Failed to read line");
50 
51     let n = input_string.trim().to_string();
52     let ret = write_the_number(n);
53     for i in 0..ret.len() {
54         if i == ret.len() - 1 {
55             print!("{}", ret.get(i).unwrap());
56         }else {
57             print!("{} ", ret.get(i).unwrap());
58         }
59     }
60 }

GIthub Link: https://github.com/DaviRain-Su/my_rust_road/blob/master/pat_solution/src/lib.rs

原文地址:https://www.cnblogs.com/Davirain/p/13544156.html