In C#:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace RomanNumerConverter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1\_Click(object sender, EventArgs e)
{
Hashtable ht = new Hashtable(); // Create a look-up table to look up Roman numerals and get there associated values.
ht.Add('M', 1000);
ht.Add('D', 500);
ht.Add('C', 100);
ht.Add('L', 50);
ht.Add('X', 10);
ht.Add('V', 5);
ht.Add('I', 1);
String RomanNumber = textBox1.Text;
int value = 0;
for (int index = 0; index < RomanNumber.Length; index++) // Go through the entered Roman numeral a character at a time
{
int nextVal;
int currentVal = Convert.ToInt32(ht\[RomanNumber\[index\]\]); // Get the value of the current character.
if (index + 1 < RomanNumber.Length) // if you are not at the end of the string
{
nextVal = Convert.ToInt32(ht\[RomanNumber\[index + 1\]\]);// Peek at the next number to see you need to use it to combine characters for a single value(e.g. IV equates to 4)
}
else
{
nextVal = 0; // No more characters so just set this to 0 to simplfy the algorithm.
}
if (nextVal > currentVal)// If the value of nextVal is greater than currentVal, we have a subtractive situation (e.g. IV)
{
currentVal = nextVal - currentVal; // To determine the value you have to subtract the value of the first number of the pair from the second number(e.g. IV = 5 - 1 = 4)
index++;// Used nextVal to help determine the number so increment the index to skip over that character in the next iteration.
}
value += currentVal; // Add the values of the Roman numerals up.
}
label1.Text = value.ToString(); //Convert the sum to string to use as a text label. This is the converted number in Arabic numerals.
}
}
}