Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d968f3c

Browse files
author
ruislan
committed
solved q273
1 parent 1dafc9c commit d968f3c

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

‎src/q/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ mod q258;
165165
mod q263;
166166
mod q264;
167167
mod q268;
168+
mod q273;
168169
mod q274;
169170
mod q275;
170171
mod q278;

‎src/q/q273.rs‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /