Rust: codewars的Roman Numerals Encoder
算法很简单,其实就是输入一个阿拉伯数字,输出一个罗马数字。
说明:但是这个只是一个简单的版本,输入的数字不算大,不涉及相对较大数的复杂罗马数字表达(比如,上面带横线之类)。
比如:
1990 =>:1000=M, 900=CM, 90=XC; => MCMXC.
2008 => 2000=MM, 8=VIII; => MMVIII.
1666 => MDCLXVI.
1、一些提示
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
2、同一个字符,最多可以重复3次。
3、40,400的可以分别用XL,CD来表达。
其它的说明,可以找度娘。
一、我的算法
fn num_as_roman(num: i32) -> String {let data: HashMap<i32, &str> = [(0, ""),(1, "I"),(2, "II"),(3, "III"),(4, "IV"),(5, "V"),(6, "VI"),(7, "VII"),(8, "VIII"),(9, "IX"),(10, "X"),(20, "XX"),(30, "XXX"),(40, "XL"),(50, "L"),(60, "LX"),(70, "LXX"),(80, "LXXX"),(90, "XC"),(100, "C"),(200, "CC"),(300, "CCC"),(400, "CD"),(500, "D"),(600, "DC"),(700, "DCC"),(800, "DCCC"),(900, "CM"),(1000, "M"),(2000, "MM"),(3000, "MMM")].into_iter().map(|w| (w.0, w.1)).collect::<HashMap<i32, &str>>();let chars: Vec<char> = num.to_string().chars().into_iter().map(|x| x).collect();let fact_nums = fact_num(num);fact_nums.into_iter().map(|x| *(data.get(&(x.0 * x.1)).unwrap())).collect::<Vec<&str>>().join("")
}
fn fact_num(num: i32) -> Vec<(i32, i32)> {let len = num.to_string().len() as i32;let mut result: Vec<(i32, i32)> = Vec::new();let mut remain: i32 = num;for i in 0..len {let k = len - i - 1;let pow_value = 10_f64.powf(k as f64) as i32;let temp = remain / pow_value;remain = remain - temp * pow_value;if k < 1 {result.push((1, temp));} else {result.push((temp, pow_value));}println!("temp :{:?}, remain:{:?}", temp, remain);}result
}
当然,也可以用 HashMap
fn num_as_roman(num: i32) -> String {let data: HashMap<i32, String> = [(0, ""),(1, "I"),(2, "II"),(3, "III"),(4, "IV"),(5, "V"),(6, "VI"),(7, "VII"),(8, "VIII"),(9, "IX"),(10, "X"),(20, "XX"),(30, "XXX"),(40, "XL"),(50, "L"),(60, "LX"),(70, "LXX"),(80, "LXXX"),(90, "XC"),(100, "C"),(200, "CC"),(300, "CCC"),(400, "CD"),(500, "D"),(600, "DC"),(700, "DCC"),(800, "DCCC"),(900, "CM"),(1000, "M"),(2000, "MM"),(3000, "MMM")].into_iter().map(|w| (w.0, w.1.to_string())).collect::<HashMap<i32, String>>();let chars: Vec<char> = num.to_string().chars().into_iter().map(|x| x).collect();let fact_nums = fact_num(num);fact_nums.into_iter().map(|x| (&data).get(&(x.0 * x.1)).unwrap().to_string()).collect::<Vec<String>>().join("")
}
二、精彩的算法
fn rep(c: char, n: usize) -> String {std::iter::repeat(c).take(n).collect()
}fn roman(d: u8, p: usize) -> String {let nines = ["IX", "XC", "CM"];let fives = ["V", "L", "D"];let fours = ["IV", "XL", "CD"];let ones = ['I', 'X', 'C', 'M'];match d {0 => String::from(""),9 => String::from(nines[p]),n if n > 5 => String::from(fives[p]) + &rep(ones[p], (n - 5) as usize),5 => String::from(fives[p]),4 => String::from(fours[p]),n => rep(ones[p], n as usize),}
}fn num_as_roman(num: i32) -> String {let s = num.to_string();let l = s.len();let mut r = String::new();for (i, d) in s.chars().enumerate() {let p = (l - i - 1) as usize;r += &roman(d.to_digit(10).unwrap() as u8, p);}r
}
2、
const ONES: [&'static str; 10] = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
const TENS: [&'static str; 10] = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];
const HUNS: [&'static str; 10] = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];
const TOUS: [&'static str; 10] = ["", "M", "MM", "MMM", "", "", "", "", "", ""];
const DIGITS: [[&'static str; 10]; 4] = [ONES, TENS, HUNS, TOUS];fn num_as_roman(num: i32) -> String {[num/1000, num/100, num/10, num].into_iter().enumerate().map(|(i, &d)| DIGITS[3 - i][(d % 10) as usize]).collect()
}
3、
static ROMAN_DEC: [(&'static str, i32); 13] = [("M", 1000), ("CM", 900), ("D", 500), ("CD", 400),("C", 100), ("XC", 90), ("L", 50), ("XL", 40),("X", 10), ("IX", 9), ("V", 5), ("IV", 4),("I", 1)];/// Converts a number to a string representating roman numeral.
fn num_as_roman(num: i32) -> String {let mut num = num;let mut result = String::new();for &(ref lit, val) in &ROMAN_DEC {while num >= val {result.push_str(lit);num -= val;}if num == 0 { break }}result
}
Rust: codewars的Roman Numerals Encoder相关推荐
- 【Python CheckiO 题解】Roman Numerals
CheckiO 是面向初学者和高级程序员的编码游戏,使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务,从而提高你的编码技能,本博客主要记录自己用 Python 在闯关时的做题思 ...
- python:实现roman numerals罗马数字算法(附完整源码)
python:实现roman numerals罗马数字算法 def roman_to_int(roman: str) -> int:vals = {"I": 1, " ...
- Codewars一些积累No.3 从罗马数字编码器来初探string的实用用法
文章目录 1.开头 2.具体先看题目内容 1)要求 2)例子 3.我的又一次头秃探索 1)认识罗马数字计数方法 2)认识基本string操作 1.字符串的生成 2.字符串的大小和容量 3.string ...
- LeetCode: 13. Roman to Integer
051106 题目 Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol ...
- # LeetCode集锦(四) - 第13题 Roman To Integer
LeetCode集锦(四) - 第13题 Roman To Integer 问题 Roman numerals are represented by seven different symbols: ...
- 【LeetCode算法题库】Day5:Roman to Integer Longest Common Prefix 3Sum
[Q13] Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Valu ...
- leetcode 12 ,13 Integer to Roman amp;amp;Roman to Integer 罗马与阿拉伯数组转换
12 Integer to Roman 13 Roman to Integer 有可能不注意的结果: class Solution {public:/*1.相同的数字连写,所表示的数等于这些数字相加得 ...
- LeetCode刷题实战(13):Roman to Integer
题目描述: 13 Roman to Integer 49.5% Easy Roman numerals are represented by seven different symbols: I, ...
- LeetCode算法入门- Roman to Integer Integer to Roman -day8
LeetCode算法入门- Roman to Integer -day8 Roman to Integer: 题目描述: Roman numerals are represented by seven ...
- C#LeetCode刷题之#13-罗马数字转整数(Roman to Integer)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3842 访问. 罗马数字包含以下七种字符: I, V, X, L, ...
最新文章
- PostSharp AOP编程:1.基于PostSharp的AOP日志记录和异常捕捉【附带源码】
- oracle导入导出命令
- dfs时间复杂度_吊打DFS和BFS,什么情况下可以用二分?
- J-LINK序列号修改
- context-param和init-param的区别
- hdu 2523 SORT AGAIN
- VC 使用 MinGW编写的dll
- Python入门到精通(一):入门必备知识
- VM ESXI安装英伟达显卡驱动
- Spring整合mybatis事务管理
- 用DEV-C++写一个走迷宫小游戏1.2最终版(完结,撒花)
- MFC中资源视图不能打开
- Palantir分析:「商业模式画布」、「SWOT」、「垄断特征」、以及「7个商业模式」
- android dd命令,【测试人员技能】Android shell 下dd命令浅析
- 大学计算机专业英语期末考试,河南大学计算机专业英语试题
- 【Python CUDA版】河北工业大学计算机图像处理实验四:频域平滑与锐化
- Android中list常用方法,Android中的常用控件及其基本用法
- MySql学习笔记(2)--数据库操作及数据管理
- excel数据平均分配给多人_如何将excel表格中的一列数字平均分配成几组,分组后每组的平均值大致相同...
- Java学习手册:Java是否支持多继承?为什么?