-
Notifications
You must be signed in to change notification settings - Fork 0
/
roman_to_Int.go
85 lines (71 loc) · 2.01 KB
/
roman_to_Int.go
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
package main
/**
* @description 13. 罗马数字转整数
* @author chengzw
* @since 2022/5/17
* @link https://leetcode.cn/problems/roman-to-integer/
*/
/**
罗马数字包含以下七种字符: I, V, X, L, C, D 和 M。
字符 数值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
例如, 罗马数字 2 写做 II, 即为两个并列的 1。 12 写做 XII, 即为 X + II。 27 写做 XXVII, 即为 XX + V + II。
通常情况下, 罗马数字中小的数字在大的数字的右边。 但也存在特例, 例如 4 不写做 IIII, 而是 IV。 数字 1 在数字 5 的左边, 所表示的数等于大数 5 减小数 1 得到的数值 4。 同样地, 数字 9 表示为 IX。 这个特殊的规则只适用于以下六种情况:
I 可以放在 V(5) 和 X(10) 的左边, 来表示 4 和 9。
X 可以放在 L(50) 和 C(100) 的左边, 来表示 40 和 90。
C 可以放在 D(500) 和 M(1000) 的左边, 来表示 400 和 900。
给定一个罗马数字, 将其转换成整数。
示例 1:
输入: s = "III"
输出: 3
示例 2:
输入: s = "IV"
输出: 4
示例 3:
输入: s = "IX"
输出: 9
示例 4:
输入: s = "LVIII"
输出: 58
解释: L = 50, V = 5, III = 3.
示例 5:
输入: s = "MCMXCIV"
输出: 1994
解释: M = 1000, CM = 900, XC = 90, IV = 4.
*/
/**
思路:
1.通常情况下,罗马数字中小的数字在大的数字的右边,如果满足该情况,累加每个字符对应的数值即可。
例如:XXVII = X + X + V + I + I = 10 + 10 + 5 + 1 + 1 = 27
2.如果存在小的数字在大的数字左边的情况,将该数字的符号取反。
例如 XIV = X - I + V = 10 - 1 + 5 = 14
时间复杂度:O(n),其中 n 是字符串 s 的长度。
空间复杂度:O(1)。
*/
var symbolValues = map[byte]int{
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
func romanToInt(s string) (ans int) {
n := len(s)
for i := range s {
value := symbolValues[s[i]]
if i < n-1 && value < symbolValues[s[i+1]] {
ans -= value
} else {
ans += value
}
}
return
}