我试图弄清楚如何将罗马数字转换为整数 [英] I am trying to figure out how to convert roman numerals into integers
问题描述
我试图弄清楚如何将罗马数字转换为整数.这是我的代码的一部分.当我提示用户输入M时,它显示1000,但是当我提示用户输入罗马数字(例如VM)时,它不会给我995,而是1005.这是因为我要告诉程序执行该操作.
I am trying to figure out how to convert roman numerals to integers. This is a portion of my code. When I prompt the user to enter M it shows 1000, but when I prompt the user to enter a roman numeral such as VM, it does not give me 995 but instead 1005. This is because I am telling my program to do just that.
我要弄清楚的是如何向前看并知道它是在添加还是减去罗马数字.
What I am trying to figure out is how I can look ahead and get it to know when it is adding or subtracting roman numerals.
我如何开始这样做?
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;
}
}
}
}
推荐答案
转换罗马数字的诀窍是向后(从字符串的末尾开始)而不是向后工作,从而简化了许多工作.
the trick to converting roman numerals is to work backwards (from the end of the string) not forwards, makes it a lot easier.
例如,如果您有IX
- 您以X开头= 10
- 移回1 ....现在它的I,我小于X,所以现在减去1 = 9
参考解决方案....
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 doesn't validate roman numerals, just convert ones that are already valid.
这篇关于我试图弄清楚如何将罗马数字转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!