Skip to content

Commit e5a3e84

Browse files
committed
roman to insteger
1 parent 7fe92bf commit e5a3e84

File tree

2 files changed

+13
-20
lines changed

2 files changed

+13
-20
lines changed

Diff for: problems/0013.roman-to-integer/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,5 @@ Example 5:
4242
Input: "MCMXCIV"
4343
Output: 1994
4444
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
45+
46+
- 倒序遍历,当遇到左边元素比右边小的时候就减掉

Diff for: problems/0013.roman-to-integer/run.go

+11-20
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,31 @@
11
package integer
22

3-
import "fmt"
4-
53
// 到着遍历?
64
func romanToInt(s string) int {
75
k := 0
86
ls := len(s)
97
if ls == 0 {
108
return k
119
}
12-
roman := map[string]int{
13-
"I": 1,
14-
"V": 5,
15-
"X": 10,
16-
"L": 50,
17-
"C": 100,
18-
"D": 500,
19-
"M": 1000,
10+
roman := map[byte]int{
11+
'I': 1,
12+
'V': 5,
13+
'X': 10,
14+
'L': 50,
15+
'C': 100,
16+
'D': 500,
17+
'M': 1000,
2018
}
21-
getRoman := func(k string) int {
22-
if v, ok := roman[k]; ok {
19+
getRoman := func(b byte) int {
20+
if v, ok := roman[b]; ok {
2321
return v
2422
}
2523
return 0
2624
}
2725

28-
if ls == 1 {
29-
k = getRoman(s)
30-
return k
31-
}
32-
3326
tn := 0
3427
for i := ls - 1; i >= 0; i-- {
35-
tmp := getRoman(string(s[i]))
36-
37-
fmt.Println("/", tmp)
28+
tmp := getRoman(s[i])
3829

3930
if tmp < tn {
4031
k -= tmp

0 commit comments

Comments
 (0)