Roman numerals are represented by seven different symbols: I, V, X, L, C, D, M.
/*
* Roman numerals are represented by seven different symbols: I, V, X, L, C, D, M.
*
* Symbol Value
* I 1
* V 5
* X 10
* L 50
* C 100
* D 500
* M 1000
*
* Input : "III"
* Output : 3
*
* Input : "IV"
* Output : 4
*
* Input : "LVIII"
* Output : 58
*
* Input : "MCMXCIV"
* Output : 1994
*/
public int LeetCode_13(string s)
{
int ans = 0;
string[] s1 = {"I", "V", "X", "L", "C", "D", "M"};
string[] s2 = { "IV", "IX", "XL", "XC", "CD", "CM" };
int[] buf_1 = new int[7];
int[] buf_2 = new int[6];
int[] gain_1 = { 1, 5, 10, 50, 100, 500, 1000 };
int[] gain_2 = { 4, 9, 40, 90, 400, 900 };
bool Is_s2 = false;
//初始化陣列
for (int i = 0; i < 7; i++)
buf_1[i] = 0;
for (int i = 0; i < 6; i++)
buf_2[i] = 0;
//收尋字串
for(int i=0; i<s.Length; i++)
{
Is_s2 = false;
for (int j = 0; j < 6; j++)
{
if((s.Length-i)>=2)
if(s.Substring(i,2) == s2[j])
{
buf_2[j]++;
i++;
Is_s2 = true;
break;
}
}
if(Is_s2 != true)
{
for (int j = 0; j < 7; j++)
{
if(s.Substring(i,1) == s1[j])
{
buf_1[j]++;
break;
}
}
}
}
//計算值
for (int i = 0; i < 7; i++)
ans += buf_1[i] * gain_1[i];
for (int i = 0; i < 6; i++)
ans += buf_2[i] * gain_2[i];
return ans;
}