File tree Expand file tree Collapse file tree 2 files changed +13
-20
lines changed
problems/0013.roman-to-integer Expand file tree Collapse file tree 2 files changed +13
-20
lines changed Original file line number Diff line number Diff line change @@ -42,3 +42,5 @@ Example 5:
4242Input: "MCMXCIV"
4343Output: 1994
4444Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
45+
46+ - 倒序遍历,当遇到左边元素比右边小的时候就减掉
Original file line number Diff line number Diff line change 11package integer
22
3- import "fmt"
4-
53// 到着遍历?
64func 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
You can’t perform that action at this time.
0 commit comments