Converting integers to roman numerals

前端 未结 29 2528
走了就别回头了
走了就别回头了 2020-12-02 09:16

I\'m trying to write a function that converts numbers to roman numerals. This is my code so far; however, it only works with numbers that are less than 400. Is there a quick

29条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 09:33

    Here is the version from @Cammilius converted to C# - works for me on low numbers which is all I need for my usecase.

    public String convertToRoman(int num)
    {    
        //Roman numerals to have <= 3 consecutive characters, the distances between deciaml values conform to this
        int[] decimalValue = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
        string[] romanNumeral = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
        int num_cp = num; // copy the function parameter into num_cp
        String result = "";
    
        for (var i = 0; i < decimalValue.Length; i = i + 1)
        { //itarate through array of decimal values
            //iterate more to find values not explicitly provided in the decimalValue array
            while (decimalValue[i] <= num_cp)
            {
                result = result + romanNumeral[i];
                num_cp = num_cp - decimalValue[i];
            }
        }
        return result;
    }
    

提交回复
热议问题