|
| 1 | +use crate::q::Solution; |
| 2 | + |
| 3 | +#[allow(unused)] |
| 4 | +impl Solution { |
| 5 | + pub fn number_to_words(num: i32) -> String { |
| 6 | + // 方法1 |
| 7 | + // 3位算一组,然后每组里面计算百十个,然后外面得到十亿,百万,千 |
| 8 | + // 每组里面又分为了20以内(因为英文20以内是单个单词),20-100,以及100以上 |
| 9 | + // AC 0ms 2mb |
| 10 | + let singles = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]; |
| 11 | + let teens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]; |
| 12 | + let tens = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]; |
| 13 | + let thousands = ["", "Thousand", "Million", "Billion"]; |
| 14 | + let to_english = |mut num: usize| -> String { |
| 15 | + let mut curr = String::new(); |
| 16 | + let mut hundred = num / 100; |
| 17 | + num %= 100; |
| 18 | + if hundred != 0 { |
| 19 | + curr.push_str(singles[hundred]); |
| 20 | + curr.push_str(" Hundred "); |
| 21 | + } |
| 22 | + let ten = num / 10; |
| 23 | + if ten >= 2 { |
| 24 | + curr.push_str(tens[ten]); |
| 25 | + curr.push(' '); |
| 26 | + num %= 10; |
| 27 | + } |
| 28 | + if num > 0 && num < 10 { |
| 29 | + curr.push_str(singles[num]); |
| 30 | + curr.push(' '); |
| 31 | + } else if num >= 10 { |
| 32 | + curr.push_str(teens[num - 10]); |
| 33 | + curr.push(' '); |
| 34 | + } |
| 35 | + return curr; |
| 36 | + }; |
| 37 | + |
| 38 | + if num == 0 { return String::from("Zero"); } |
| 39 | + let mut ans = String::new(); |
| 40 | + let mut i = 3; |
| 41 | + let mut unit = 1000000000; |
| 42 | + let mut num = num; |
| 43 | + while i < 4 && i >= 0 { |
| 44 | + let mut cur_num = num / unit; |
| 45 | + if cur_num != 0 { |
| 46 | + num -= cur_num * unit; |
| 47 | + ans.push_str(&to_english(cur_num as usize)); |
| 48 | + ans.push_str(thousands[i]); |
| 49 | + ans.push(' '); |
| 50 | + } |
| 51 | + unit /= 1000; |
| 52 | + i -= 1; |
| 53 | + } |
| 54 | + ans.trim().to_string() |
| 55 | + } |
| 56 | +} |
0 commit comments