Skip to content

Commit 75e48f4

Browse files
committed
Algorithms: Roman to Integer
1 parent bfe5a4f commit 75e48f4

File tree

3 files changed

+57
-1
lines changed

3 files changed

+57
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# LeetCode
22

3-
![Problems Solved](https://img.shields.io/badge/Problems%20Solved-13%20%2F%202046-1f425f?logo=leetcode)
3+
![Problems Solved](https://img.shields.io/badge/Problems%20Solved-14%20%2F%202046-1f425f?logo=leetcode)
44
![Language: Golang](https://img.shields.io/badge/language-Golang-00ADD8?logo=go)
55

66
### LeetCode Algorithm
@@ -11,6 +11,7 @@
1111
| 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [Go](go/0002_add_two_numbers) | 🟡 |
1212
| 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [Go](go/0007_reverse_integer) | 🟡 |
1313
| 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Go](go/0009_palindrome_number) | 🟢 |
14+
| 13 | [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [Go](go/0013_roman_to_integer) | 🟢 |
1415
| 17 | [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) | [Go](go/0017_letter_combinations_phone) | 🟡 |
1516
| 20 | [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | [Go](go/0020_valid_parentheses) | 🟢 |
1617
| 35 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [Go](go/0035_search_insert_position) | 🟢 |
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package roman_to_integer
2+
3+
var numsMap = map[byte]int{
4+
'I': 1,
5+
'V': 5,
6+
'X': 10,
7+
'L': 50,
8+
'C': 100,
9+
'D': 500,
10+
'M': 1000,
11+
}
12+
13+
func romanToInt(s string) int {
14+
result, sLen := 0, len(s)
15+
for i := 0; i < sLen; i++ {
16+
num := numsMap[s[i]]
17+
if i > 0 {
18+
prevNum := numsMap[s[i-1]]
19+
if prevNum < num && (num/prevNum == 5 || num/prevNum == 10) {
20+
result += num - prevNum - prevNum
21+
continue
22+
}
23+
}
24+
result += num
25+
}
26+
27+
return result
28+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package roman_to_integer
2+
3+
import "testing"
4+
5+
func Test_romanToInt(t *testing.T) {
6+
tests := []struct {
7+
input string
8+
want int
9+
}{
10+
{input: "I", want: 1},
11+
{input: "III", want: 3},
12+
{input: "IV", want: 4},
13+
{input: "VI", want: 6},
14+
{input: "IX", want: 9},
15+
{input: "LVIII", want: 58},
16+
{input: "MCMXCIV", want: 1994},
17+
{input: "MMMCMXCIX", want: 3999},
18+
{input: "MMMCCCXXXIII", want: 3333},
19+
}
20+
21+
for i, tc := range tests {
22+
got := romanToInt(tc.input)
23+
if tc.want != got {
24+
t.Fatalf("Case #%d: expected: %v, got: %v", i+1, tc.want, got)
25+
}
26+
}
27+
}

0 commit comments

Comments
 (0)