Converting integers to roman numerals

前端 未结 29 2535
走了就别回头了
走了就别回头了 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条回答
  •  不知归路
    2020-12-02 09:57

    While I liked Mosè Bottacini's answer, using recursion has a couple of negative side effects in this scenario. One being the possible stack overflow, hence his limiting of the upper bound of the number. While, yes, I realize how ridiculous a huge number looks in roman numerals, this is still a limitation that is not necessary to achieve the result.

    Also, since strings are immutable, his version is going to be very memory inefficient, due to the heavy use of string concatenation. Below is my modified version of his method, using just a while loop and a StringBuilder. My version should actually be more performant (although we're talking about differences in the sub-millisecond range) and much easier on system memory.

    public static string ToRomanNumeral(this int value)
    {
        if (value < 0)
            throw new ArgumentOutOfRangeException("Please use a positive integer greater than zero.");
    
        StringBuilder sb = new StringBuilder();
        int remain = value;
        while (remain > 0)
        {
            if (remain >= 1000) { sb.Append("M"); remain -= 1000; }
            else if (remain >= 900) { sb.Append("CM"); remain -= 900; }
            else if (remain >= 500) { sb.Append("D"); remain -= 500; }
            else if (remain >= 400) { sb.Append("CD"); remain -= 400; }
            else if (remain >= 100) { sb.Append("C"); remain -= 100; }
            else if (remain >= 90) { sb.Append("XC"); remain -= 90; }
            else if (remain >= 50) { sb.Append("L"); remain -= 50; }
            else if (remain >= 40) { sb.Append("XL"); remain -= 40; }
            else if (remain >= 10) { sb.Append("X"); remain -= 10; }
            else if (remain >= 9) { sb.Append("IX"); remain -= 9; }
            else if (remain >= 5) { sb.Append("V"); remain -= 5; }
            else if (remain >= 4) { sb.Append("IV"); remain -= 4; }
            else if (remain >= 1) { sb.Append("I"); remain -= 1; }
            else throw new Exception("Unexpected error."); // <<-- shouldn't be possble to get here, but it ensures that we will never have an infinite loop (in case the computer is on crack that day).
        }
    
        return sb.ToString();
    }
    

提交回复
热议问题