Skip to content

Commit 920b018

Browse files
Navid2zpcclauss
andauthored
Added roman to integer conversion (#240)
* Create roman_to_integer.go * test for roman to integer conversion * Delete countingsort.go Co-authored-by: Christian Clauss <[email protected]>
1 parent 5110300 commit 920b018

File tree

3 files changed

+54
-27
lines changed

3 files changed

+54
-27
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
This algorithm will convert a standard roman number to an integer
3+
https://en.wikipedia.org/wiki/Roman_numerals
4+
Function receives a string as a roman number and outputs an integer
5+
Maximum output will be 3999
6+
Only standard form is supported
7+
*/
8+
package conversions
9+
10+
var romans = map[string]int{"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
11+
12+
func RomanToInteger(roman string) int {
13+
total := 0
14+
holder := 0
15+
for holder < len(roman) {
16+
if holder+1 < len(roman) && (romans[string(roman[holder])] < romans[string(roman[holder+1])]) {
17+
total += romans[string(roman[holder+1])] - romans[string(roman[holder])]
18+
holder += 2
19+
} else {
20+
total += romans[string(roman[holder])]
21+
holder++
22+
}
23+
}
24+
return total
25+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package conversions
2+
3+
import "testing"
4+
5+
type romanToIntegerConversionTest struct {
6+
input string
7+
expected int
8+
name string
9+
}
10+
11+
var romanToIntegerTests = []romanToIntegerConversionTest{
12+
{input: "DCCLXXXIX", expected: 789, name: "DCCLXXXIX-789"},
13+
{input: "MLXVI", expected: 1066, name: "MLXVI-1066"},
14+
{input: "MCMXVIII", expected: 1918, name: "MCMXVIII-1918"},
15+
{input: "V", expected: 5, name: "V-5"},
16+
}
17+
18+
func TestRomanToInteger(t *testing.T) {
19+
20+
for _, test := range romanToIntegerTests {
21+
convertedValue := RomanToInteger(test.input)
22+
if convertedValue != test.expected {
23+
t.Errorf(
24+
"roman to integer test %s failed. expected '%d' but got '%d'",
25+
test.name, test.expected, convertedValue,
26+
)
27+
}
28+
}
29+
}

sorts/countingsort.go

Lines changed: 0 additions & 27 deletions
This file was deleted.

0 commit comments

Comments
 (0)