Skip to content

Instantly share code, notes, and snippets.

@ylem
Last active November 18, 2016 09:48
Show Gist options
  • Save ylem/22643286d691383dd4a8a23134e993db to your computer and use it in GitHub Desktop.
Save ylem/22643286d691383dd4a8a23134e993db to your computer and use it in GitHub Desktop.
Roman To Arabic
using System;
using NUnit.Framework;
namespace RomanTest
{
public class RomanArabic
{
public RomanArabic() { }
[TestCase("M", 1000)]
[TestCase("D", 500)]
[TestCase("I", 1)]
[TestCase("II", 2)]
[TestCase("IV", 4)]
[TestCase("IX", 9)]
[TestCase("XI", 11)]
[TestCase("XIX", 19)]
[TestCase("XCIX", 99)]
[TestCase("MCMXLIX", 1949)]
public void RomanArabicTest(String roman, int arabic)
{
var result = new Romanumberal().ConvertToArabic(roman);
Assert.That(result, Is.EqualTo(arabic));
}
}
}
using System;
using System.Collections.Generic;
namespace RomanTest
{
public class Romanumberal
{
private Dictionary<char, int> romanarabic = new Dictionary<char, int>() {
{'M', 1000},
{'D', 500},
{'C', 100},
{'L', 50},
{'X', 10},
{'V', 5},
{'I', 1},
};
public int ConvertToArabic(String roman)
{
var total = 0;
var chars = roman.ToCharArray();
for (int i = 0; i < chars.Length; i++) {
bool isNotLastChar = i < chars.Length - 1;
int currentIndexValue = romanarabic[chars[i]];
int nextIndexValue = isNotLastChar ? romanarabic[chars[i + 1]] : 0;
int counter = currentIndexValue < nextIndexValue ? -1 : 1;
total += (currentIndexValue * counter);
}
return total;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment