I'm trying to figure out how to convert roman numbers to integers

I am trying to figure out how to convert Roman numerals to integers. This is part of my code. When I suggest the user to enter M, it shows 1000, but when I offer the user to enter a Roman numeral, such as VM, it does not give me 995, but instead of 1005. This is because I say that my program does just that.

What I'm trying to understand is how I can look to the future and find out when it adds or subtracts Roman numerals.

How do I start doing this?

class Roman { public int inprogress = 0; public Roman(string roman) { char temp = 'Z'; int length; length = roman.Length; for (int i = 0; i < length; i++) { temp = roman[i]; if (temp == 'M') { inprogress = inprogress + 1000; } if (temp == 'D') { inprogress = inprogress + 500; } if (temp == 'C') { inprogress = inprogress + 100; } if (temp == 'L') { inprogress = inprogress + 50; } if (temp == 'X') { inprogress = inprogress + 10; } if (temp == 'V') { inprogress = inprogress + 5; } if (temp == 'I') { inprogress = inprogress + 1; } } } } 
+6
source share
3 answers

The trick for converting Roman numerals is to work backward (from the end of the line) and not forward, making it a lot easier.

for example if you have IX

  • you start with X, = 10
  • return back 1 .... now its I, I am less than X, so now we subtract 1 = 9

Reference solution ....

 public class RomanNumeral { public static int ToInt(string s) { var last = 0; return s.Reverse().Select(NumeralValue).Sum(v => { var r = (v >= last)? v : -v; last = v; return r; }); } private static int NumeralValue(char c) { switch (c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; } return 0; } } 

NOTE: this does not check Roman numerals, just convert those that are already valid.

+11
source
  List<Level> levels = new List<Level>(); int[] val = new int[255]; private void Form1_Load(object sender, EventArgs e) { val[(byte)'I'] = 1; val[(byte)'V'] = 5; val[(byte)'X'] = 10; val[(byte)'L'] = 50; val[(byte)'C'] = 100; val[(byte)'D'] = 500; val[(byte)'M'] = 1000; levels.Clear(); levels.Add(new Level('I', 'V', 'X')); levels.Add(new Level('X', 'L', 'C')); levels.Add(new Level('C', 'D', 'M')); } int fromRoman(string n) { n = n.ToUpper(); var result = 0; var lastDigit = 0; for (var pos = n.Length - 1; pos >= 0; pos--) { var curDigit = val[(byte)n[pos]]; if (curDigit >= lastDigit) result += curDigit; else result -= curDigit; lastDigit = curDigit; } return result; } public class Level { public Level(char i, char v, char x) { this.i = i; this.x = x; this.v = v; } public char i; public char v; public char x; } 

Then run

 int Result = fromRoman("X"); 
+1
source

You need to add logic, which basically says that if V is before M, then subtract it. Based on this line here:

if (temp == 'V') {inprogress = inprogress + 5;

0
source

Source: https://habr.com/ru/post/949690/


All Articles