Tuesday, April 25, 2017

[C#] Roman numerals converter - 羅馬數字轉換

Two little function can translate Roman Numerals(String) to Number(Int) and trans back.
兩個小function可以將羅馬數字(字串)轉成數字(整數)再轉回

//1990=>MCMXC
public static string IntToRoman(int num)
{
 String[] m = { "", "M", "MM", "MMM" };
 String[] c = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
 String[] x = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
 String[] i = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
 return m[num / 1000] + c[(num % 1000) / 100] + x[(num % 100) / 10] + i[num % 10];
}

//MCMXC=>1990
public static int RomanToInt(string s)
{
 Dictionary d1 = new Dictionary { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 } };
 Dictionary d2 = new Dictionary { { "IV", 4 }, { "IX", 9 }, { "XL", 40 }, { "XC", 90 }, { "CD", 400 }, { "CM", 900 } };
 int num = 0;
 foreach (var d in d2)
 {
  if (s.Contains(d.Key))
  {
   num += d.Value;
   s = s.Replace(d.Key, "");
  }
 }
 foreach (var d in d1)
 {
  var c = s.Count(x => x == d.Key);
  if (c > 0)
  {
   num += d.Value * c;
  }
 }
 return num;
}

4 comments:

  1. I bought this copy of Jimmy Choo shoes and clothes from this store.cheap jimmy choo uk The quality is great. I have repurchased it many times. I recommend it to my friends. replica jimmy choo booties They all praise the quality of the shoes and the service attitude of the store.

    ReplyDelete
  2. Montblanc Meisterstück Geometric Solitaire Platinum Ballpoint Pen is the ideal writing tool for you to impress. This replica mont blanc fountain pen medium has proven to be replica montblanc heritage collection very popular among collectors because it is larger than a standard Classique ballpoint pen, but smaller than a large LeGrand pen, so it can be easily held in your hand. Each writing instrument in the series has more than 2,000 geometric facets, giving them a unique optical illusion that makes your eyes charming and fun. The geometry of Taipan Solitaire was born from the desire to combine Montblanc classic design with unique materials.

    ReplyDelete
  3. Le magasin a résolu le problème pour moi, et le service est très patient,Moncler Jas Verkoop c'est une expérience de magasinage parfaite. Quand j'ai reçu la tenue Moncler, je pensais que c'était une bonne réplique de la doudoune Moncler.Goedkope dames Moncler jas J'aime cette boutique en ligne, cette robe Moncler est simple et élégante. Très satisfait de cet achat.

    ReplyDelete
  4. I have been paying attention to replica watches. After receiving the goods, replica rolex uk I was very surprised. The leather strap is comfortable, the watch is light weight, high quality, and the price is good.replica omega constellation watches If you are looking for a watch that is suitable for your daily wear, this replica watch is definitely a perfect clothing match. I will buy again!

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...