#codingexercise
int RomanToInt(string s)
{
if (String.IsNullOrEmpty(s)) return 0;
//regex match string with +[IVXLCDM]
var dict = new Dictionary<char, int> ();
dict['I'] = 1;
dict['V'] = 5;
dict['X'] = 10;
dict['L'] = 50;
dict['C'] = 100;
dict['D'] = 500;
dict['M'] = 1000;
int ret = 0;
char temp;
stack<char> st;
st.push(s[0]);
for (int I = 1; I< s.Length; I++)
{
if (st.count > 0 && dict[s[I]] > dict[st.Peek()])
{
temp = st.top();
st.pop();
ret = ret - dict[temp];
st.Push(s[I]);
}
else
st = st.Push(s[I]);
}
while(!st.empty)
{
ret += m[ st.Peek()];
st.pop();
}
return ret;
}
// there are other ways of doing this but I'm just listing the earliest one.
int RomanToInt(string s, int index, Dictionary<char, int> dict)
{
// validate s as not empty, not null and roman numerals only
if (index == s.length) return 0;
if (index - 1 > 0 && dict[s[index]] > dict[s[index-1]])
return (0-2 * dict[s[Index-1]]) + dict[s[Index]] + RomanToInt(s, index+1, dict);
else
return dict[s[Index]] + RomanToInt(s, index + 1, dict);
}
int RomanToInt(string s)
{
if (String.IsNullOrEmpty(s)) return 0;
//regex match string with +[IVXLCDM]
var dict = new Dictionary<char, int> ();
dict['I'] = 1;
dict['V'] = 5;
dict['X'] = 10;
dict['L'] = 50;
dict['C'] = 100;
dict['D'] = 500;
dict['M'] = 1000;
int ret = 0;
char temp;
stack<char> st;
st.push(s[0]);
for (int I = 1; I< s.Length; I++)
{
if (st.count > 0 && dict[s[I]] > dict[st.Peek()])
{
temp = st.top();
st.pop();
ret = ret - dict[temp];
st.Push(s[I]);
}
else
st = st.Push(s[I]);
}
while(!st.empty)
{
ret += m[ st.Peek()];
st.pop();
}
return ret;
}
// there are other ways of doing this but I'm just listing the earliest one.
int RomanToInt(string s, int index, Dictionary<char, int> dict)
{
// validate s as not empty, not null and roman numerals only
if (index == s.length) return 0;
if (index - 1 > 0 && dict[s[index]] > dict[s[index-1]])
return (0-2 * dict[s[Index-1]]) + dict[s[Index]] + RomanToInt(s, index+1, dict);
else
return dict[s[Index]] + RomanToInt(s, index + 1, dict);
}
No comments:
Post a Comment