Skip to content

Commit 545dd70

Browse files
committed
Basic Roman Numerals resolve
1 parent 942ce4f commit 545dd70

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/easy/BasicRomanNumerals.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package main
2+
3+
import "fmt"
4+
5+
// BasicRomanNumerals returns the decimal equivalent of the Roman numeral given
6+
func BasicRomanNumerals(str string) int {
7+
// Define a map to store the values of each Roman numeral
8+
romanValues := map[byte]int{
9+
'I': 1,
10+
'V': 5,
11+
'X': 10,
12+
'L': 50,
13+
'C': 100,
14+
'D': 500,
15+
'M': 1000,
16+
}
17+
18+
// Initialize the result
19+
result := 0
20+
21+
// Iterate through the Roman numeral string
22+
for i := 0; i < len(str); i++ {
23+
// Get the value of the current Roman numeral
24+
value := romanValues[str[i]]
25+
26+
// If the current numeral is smaller than the next numeral, subtract its value
27+
if i < len(str)-1 && romanValues[str[i]] < romanValues[str[i+1]] {
28+
result -= value
29+
} else {
30+
// Otherwise, add its value
31+
result += value
32+
}
33+
}
34+
35+
return result
36+
}
37+
38+
func main() {
39+
// Test cases
40+
result1 := BasicRomanNumerals("MDCXXI")
41+
fmt.Println(result1) // Output: 24
42+
43+
result2 := BasicRomanNumerals("XLVI")
44+
fmt.Println(result2) // Output: 46
45+
}

0 commit comments

Comments
 (0)