自己没想出来,看着网上JAVA改的,各位大佬勿喷,多多指教,C#的答案太少了,权当整理吧
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 罗马数字转成整数
{
class Program
{
static void Main(string[] args)
{
int num = Romantoint(Console.ReadLine());
Console.WriteLine(num);
Console.ReadKey();
}
public static int Romantoint(String s)
{
int result = 0;
char[] chars = s.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
switch (chars[i])
{
case 'M':
result += 1000;
break;
case 'D':
result += 500;
break;
case 'C':
if (i + 1 < chars.Length && chars[i + 1] == 'M')
{//确保数组不越界以及CM的特殊情况,以下几种情况同理
result += 900;
i++;//i++是为了跳过下一个字符,直接去寻找CM下一个字符
}
else if (i + 1 < chars.Length && chars[i + 1] == 'D')
{
result += 400;
i++;//同理
}
else
{
result += 100;
}
break;
case 'L':
result += 50;
break;
case 'X':
if (i + 1 < chars.Length && chars[i + 1] == 'L')
{
result += 40;
i++;
}
else if (i + 1 < chars.Length && chars[i + 1] == 'C')
{
result += 90;
i++;
}
else
{
result += 10;
}
break;
case 'V':
result += 5;
break;
case 'I':
if (i == chars.Length - 1)
{//确保数组不越界
result += 1;
break;
}
if (chars[i + 1] == 'V')
{
result += 4;
i++;
}
else if (chars[i + 1] == 'X')
{
result += 9;
i++;
}
else
{
result += 1;
}
break;
default:
break;
}
}
return result;
}
}
}
其实就是1\4\5\9\10,然后十百千,这样罗列出来,switch-case一下应该也能出来,自己能力有限,大家见谅~
转载地址:https://blog.csdn.net/myone_two/article/details/80335330