-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNo13_Math.cs
100 lines (98 loc) · 3.17 KB
/
No13_Math.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode_13
{
//static void Main(string[] args)
//{
// var solution = new Solution();
// while (true)
// {
// //int input = int.Parse(Console.ReadLine());
// string input = Console.ReadLine();
// var res = solution.RomanToInt(input);
// Console.WriteLine(res);
// }
//}
public class Solution
{
/// <summary>
/// 第一印象,遍历解(没有看到更好的做法,)
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public int RomanToInt(string s)
{
int sum = 0;
for (int i = 0; i < s.Length; i++)
{
switch (s[i])
{
case 'I':
{
if (i != s.Length - 1 && s[i + 1] == 'V')
{
sum += 4;
i++;
}
else if (i != s.Length - 1 && s[i + 1] == 'X')
{
sum += 9;
i++;
}
else
{
sum += 1;
}
break;
}
case 'V':
sum += 5; break;
case 'X':
{
if (i != s.Length - 1 && s[i + 1] == 'L')
{
sum += 40;
i++;
}
else if (i != s.Length - 1 && s[i + 1] == 'C')
{
sum += 90;
i++;
}
else
{
sum += 10;
}
break;
}
case 'L':
sum += 50; break;
case 'C':
{
if (i != s.Length - 1 && s[i + 1] == 'D')
{
sum += 400;
i++;
}
else if (i != s.Length - 1 && s[i + 1] == 'M')
{
sum += 900;
i++;
}
else
{
sum += 100;
}
break;
}
case 'D':
sum += 500; break;
case 'M': sum += 1000; break;
default: break;
}
}
return sum;
}
}
}