Skip to content

Instantly share code, notes, and snippets.

@VelocityRa
Created October 8, 2019 22:52
Show Gist options
  • Save VelocityRa/f6eb51a18c6c7037f99f4f8dc58b1063 to your computer and use it in GitHub Desktop.
Save VelocityRa/f6eb51a18c6c7037f99f4f8dc58b1063 to your computer and use it in GitHub Desktop.
const DEMO_MODE : bool = false;
fn get_digit(num: u32, index: u32) -> u8 {
(num / 10u32.pow(index) % 10) as u8
}
/* Returns true if a number was emitted */
fn emit_units_tens_hundreds(num: u32, str: &mut String) -> bool {
let units_names = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
let tens_names = ["", "ten", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"];
let tens_single_names = ["", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
let units = get_digit(num, 0) as usize;
let tens = get_digit(num, 1) as usize;
let hundreds = get_digit(num, 2) as usize;
let has_units = units > 0;
let has_tens = tens > 0;
let has_hundreds = hundreds > 0;
let is_teens = has_units && tens == 1;
if has_hundreds {
*str += format!("{} hundred ", units_names[hundreds]).as_str();
}
if has_tens {
if is_teens {
*str += format!("{} ", tens_single_names[units]).as_str();
} else {
*str += format!("{}{}", tens_names[tens], if has_units {"-"} else {" "}).as_str();
}
}
if has_units & !is_teens {
*str += format!("{} ", units_names[units]).as_str();
}
return has_units || has_tens || has_hundreds;
}
fn main() {
let input_number;
if DEMO_MODE {
input_number = 1234567890;
} else {
let mut line = String::new();
std::io::stdin().read_line(&mut line).expect("Can't read line");
input_number = line.trim().parse::<u32>().expect("Invalid number entered");
}
let mut number_str = String::new();
if input_number != 0 {
// Digits 7 to 9
let has_billions = emit_units_tens_hundreds(input_number / (1000 * 1000 * 1000), &mut number_str);
if has_billions {
number_str += "billion ";
}
// Digits 7 to 9
let has_millions = emit_units_tens_hundreds(input_number / (1000 * 1000), &mut number_str);
if has_millions {
number_str += "million ";
}
// Digits 4 to 6
let has_thousands = emit_units_tens_hundreds(input_number / 1000, &mut number_str);
if has_thousands {
number_str += "thousand ";
}
// Digits 1 to 3
emit_units_tens_hundreds(input_number, &mut number_str);
} else {
number_str += "zero";
}
println!("{}: {}", input_number, number_str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment