File tree 2 files changed +13
-20
lines changed
problems/0013.roman-to-integer
2 files changed +13
-20
lines changed Original file line number Diff line number Diff line change @@ -42,3 +42,5 @@ Example 5:
42
42
Input: "MCMXCIV"
43
43
Output: 1994
44
44
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
45
+
46
+ - 倒序遍历,当遇到左边元素比右边小的时候就减掉
Original file line number Diff line number Diff line change 1
1
package integer
2
2
3
- import "fmt"
4
-
5
3
// 到着遍历?
6
4
func romanToInt (s string ) int {
7
5
k := 0
8
6
ls := len (s )
9
7
if ls == 0 {
10
8
return k
11
9
}
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 ,
20
18
}
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 {
23
21
return v
24
22
}
25
23
return 0
26
24
}
27
25
28
- if ls == 1 {
29
- k = getRoman (s )
30
- return k
31
- }
32
-
33
26
tn := 0
34
27
for i := ls - 1 ; i >= 0 ; i -- {
35
- tmp := getRoman (string (s [i ]))
36
-
37
- fmt .Println ("/" , tmp )
28
+ tmp := getRoman (s [i ])
38
29
39
30
if tmp < tn {
40
31
k -= tmp
You can’t perform that action at this time.
0 commit comments