罗马数字到整数 [英] Roman numerals to integers
问题描述
我要转移的产品不幸的是必须与产品名称匹配.这里最大的问题是,由于罗马数字,我可能会得到重复的产品.有时,同一商品会用罗马数字命名,而其他时候则是常规商品.
I have a transfer with products that unfortunately has to get matched by product name. The biggest issue here is I might get duplicate products on account of roman numbers. Sometimes the same product will be named with a roman number, other times it will be a regular one.
我正在寻找一个可能已经完成的字符串函数来转换它,但是没有运气.我想自己做起来并不难,但是我很想听听一些有关如何处理这种情况的意见,并且如果您知道已经完成此功能的函数,请为其命名.
I was googling for maybe a already made string function to convert this, but had no luck. I guess it wouldn't be that hard to make my own, but I would love to hear some opinions on how to handle the situation, and also if you know an already made function that does this, name it.
这些产品是移动设备.示例-三星Galaxy SII-三星Galaxy S2
The products are mobile gadgets. Example - Samsung Galaxy SII - Samsung Galaxy S2
推荐答案
我在这里注意到一些非常复杂的解决方案,但这是一个非常简单的问题.我提出的解决方案避免了对异常"(IV,IX,XL等)进行硬编码的需要.我使用for
循环向前看罗马数字字符串中的下一个字符,以查看与该数字关联的数字是否应该减去或加到总数中.为简单起见,我假设所有输入均有效.
I've noticed some really complicated solutions here but this is a really simple problem. I made a solution that avoided the need to hard code the "exceptions" (IV, IX, XL, etc). I used a for
loop to look ahead at the next character in the Roman numeral string to see if the number associated with the numeral should be subtracted or added to the total. For simplicity's sake I'm assuming all input is valid.
private static Dictionary<char, int> RomanMap = new Dictionary<char, int>()
{
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
public static int RomanToInteger(string roman)
{
int number = 0;
for (int i = 0; i < roman.Length; i++)
{
if (i + 1 < roman.Length && RomanMap[roman[i]] < RomanMap[roman[i + 1]])
{
number -= RomanMap[roman[i]];
}
else
{
number += RomanMap[roman[i]];
}
}
return number;
}
我最初尝试在字符串上使用foreach
,我认为这是一个更具可读性的解决方案,但最终我将每个数字相加并相减两次(如果发现是例外之一),我没有这样做不喜欢.无论如何,我都会将其张贴在这里.
I initially tried using a foreach
on the string which I think was a slightly more readable solution but I ended up adding every single number and subtracting it twice later if it turned out to be one of the exceptions, which I didn't like. I'll post it here anyway for posterity.
public static int RomanToInteger(string roman)
{
int number = 0;
char previousChar = roman[0];
foreach(char currentChar in roman)
{
number += RomanMap[currentChar];
if(RomanMap[previousChar] < RomanMap[currentChar])
{
number -= RomanMap[previousChar] * 2;
}
previousChar = currentChar;
}
return number;
}
这篇关于罗马数字到整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!