罗马数字为整数 [英] Roman numbers 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.
我在使用Google的也许已经取得字符串函数来转换这一点,但没有运气。我想这不会是努力使我自己,但我很想听听你对如何处理这种情况的一些意见,如果你还认识一个已经取得函数,这样做,将其命名为
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
推荐答案
一个更加简单易读C#实现的:
A more simple and readable C# implementation that:
- 地图我1,V 5,X为10,L 50,C 100,D 500,男为1000。
- 使用一个单一的foreach循环(的foreach 的使用上的宗旨,与前值
保留)。 - 添加映射号到总。
- 减去两倍的号码前添加,如果I L或C,C前D或M(不是所有的字符都在这里允许!)之前V或X,X之前。
- 返回0(在罗马数字中不使用)对空字符串,打错一个字母
或不允许的字符用于减法 - 备注:这是还没有完全完成,我们没有检查所有可能的条件,一个有效的输入字符串
- maps I to 1, V to 5, X to 10, L to 50, C to 100, D to 500, M to 1000.
- uses one single foreach loop (foreach used on purpose, with previous value hold).
- adds the mapped number to the total.
- subtracts twice the number added before, if I before V or X, X before L or C, C before D or M (not all chars are allowed here!).
- returns 0 (not used in Roman numerals) on empty string, wrong letter or not allowed char used for subtraction.
- remark: it's still not totally complete, we didn't check all possible conditions for a valid input string!
代码:
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 ConvertRomanToNumber(string text)
{
int totalValue = 0, prevValue = 0;
foreach (var c in text)
{
if (!_romanMap.ContainsKey(c))
return 0;
var crtValue = _romanMap[c];
totalValue += crtValue;
if (prevValue != 0 && prevValue < crtValue)
{
if (prevValue == 1 && (crtValue == 5 || crtValue == 10)
|| prevValue == 10 && (crtValue == 50 || crtValue == 100)
|| prevValue == 100 && (crtValue == 500 || crtValue == 1000))
totalValue -= 2 * prevValue;
else
return 0;
}
prevValue = crtValue;
}
return totalValue;
}
这篇关于罗马数字为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!