Converting integers to roman numerals

前端 未结 29 2530
走了就别回头了
走了就别回头了 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:50

    First create list of Tuples which contains numbers and corresponds.
    Then a method/loops to iterate and return result.
    
    IEnumerable> data = new List>()
                    {
                      new Tuple( 1, "I"),
                      new Tuple( 4, "IV" ),
                      new Tuple( 5, "V" ),
                      new Tuple( 9, "IX" ),
                      new Tuple( 10, "X" ),
                      new Tuple( 40, "XL" ),
                      new Tuple( 50, "L" ),
                      new Tuple( 90, "XC" ),
                      new Tuple( 100, "C" ),
                      new Tuple( 400, "CD" ),
                      new Tuple( 500, "D" ),
                      new Tuple( 900, "CM"),
                      new Tuple( 1000, "M" )
                    };
    
    
     public string ToConvert(decimal num)
                { 
                     data = data.OrderByDescending(o => o.Item1).ToList(); 
                    List> subData = data.Where(w => w.Item1 <= num).ToList();
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in subData)
                    {
                        if (num >= item.Item1)
                        {
                            while (num >= item.Item1)
                            {
                                num -= item.Item1;
                                sb.Append(item.Item2.ToUpper());
                            }
                        }
                    } 
                    return sb.ToString();
                }
    

提交回复
热议问题