Converting integer to Roman Numeral

前端 未结 9 1323
轮回少年
轮回少年 2020-12-16 08:27

I have a test due in about four hours and one of the questions asks us to convert a user-inputed integer up to 100 into a roman numeral. I think my code is very close (I fou

9条回答
  •  无人及你
    2020-12-16 08:44

    I think this can actually be solved much more simply than your attempt, where frankly I fail to understand what you are trying to do (but that's me).

    Anyway, it can just be a sequence of if/else, not even nested. All you need to do is to check what is the "largest" literal contained in the input number, note it and then subtract the value if represents from the input number. Continue in such a way until you get to 0.

    e.g. (I'm not sure this is C++ syntax, but you can adjust it of course):

    string roman = ""
    if(input == 100)
    {
        roman += "C";
        input -= 100;
    }
    
    if(input >= 50)
    {
        roman += "L";
        input -= 50;
    }
    

    And so on, you can figure the rest out on your own (it's your test after all).

    Two things:

    • some literals can be repeated (3: III, 20: XX).
    • writing e.g. "XXXX" for 40 instead of "XL" is still a valid roman number (although less common), so if I were evaluating your test I would accept it, but that depends on the assignment. (http://en.wikipedia.org/wiki/Roman_numerals)

提交回复
热议问题