Answers for "roman numeral conversions"

0

roman numeral conversions

// Roman numeral conversions
fn int_to_roman(num: i32) -> String {
    let m = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
    let s = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];

    let (mut num, mut buf) = (num, vec![]);
    for i in 0..13 {
        let mut j = num / m[i];
        num %= m[i];
        while j > 0 {
            buf.push(s[i]);
            j -= 1;
        }
    }
    buf.into_iter().collect()
}

fn roman_to_int1(s: String) -> i32 {
    s.chars().rev().fold((0, 0), |(sum, prev), c| {
            let n = match c {
                'I' => 1,
                'V' => 5,
                'X' => 10,
                'L' => 50,
                'C' => 100,
                'D' => 500,
                'M' => 1000,
                _ => panic!("Not a roman numeral")};
            if n >= prev {              
                (sum + n, n)
            } else {
                (sum - n, n)
            }
        }).0
}

fn main() {
    let i = 2021;
    println!("Int {} to Roman {} to Int {}", i, int_to_roman(i), roman_to_int1(int_to_roman(i)));
}
Posted by: Guest on August-25-2021

Browse Popular Code Answers by Language