Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a923607

Browse files
Roman to Integer
1 parent 2a0a69b commit a923607

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

‎Math/Math.Lib/RomanToInteger.cs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
6+
namespace Math.Lib
7+
{
8+
// Given a roman numeral, convert it to an integer.
9+
10+
// Input is guaranteed to be within the range from 1 to 3999.
11+
public class Solution
12+
{
13+
public int RomanToInt(string s) {
14+
Dictionary<char, int> T = new Dictionary<char, int>{
15+
{ 'I' , 1 },
16+
{ 'V' , 5 },
17+
{ 'X' , 10 },
18+
{ 'L' , 50 },
19+
{ 'C' , 100 },
20+
{ 'D' , 500 },
21+
{ 'M' , 1000 }
22+
};
23+
24+
int sum = T[s[s.Length-1]];
25+
for (int i = s.Length - 2; i >= 0; --i)
26+
{
27+
if (T[s[i]] < T[s[i + 1]])
28+
{
29+
sum -= T[s[i]];
30+
}
31+
else
32+
{
33+
sum += T[s[i]];
34+
}
35+
}
36+
37+
return sum;
38+
}
39+
}
40+
41+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /