Created
May 10, 2025 03:47
-
-
Save bozdoz/23a1c974e5a9e2b9fa152b6dcdc3f00a to your computer and use it in GitHub Desktop.
roman numerals in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"strings" | |
) | |
var ( | |
to = flag.Int("to", 0, "convert int to roman") | |
from = flag.String("from", "", "convert roman to int") | |
chars = [...]string{"M", "CM", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"} | |
vals = [...]int{1000, 900, 100, 90, 50, 40, 10, 9, 5, 4, 1} | |
) | |
func fromRoman(in string) (out int) { | |
for i, char := range chars { | |
for strings.HasPrefix(in, char) { | |
out += vals[i] | |
in = strings.TrimPrefix(in, char) | |
} | |
} | |
return | |
} | |
func toRoman(in int) (out string) { | |
for i, val := range vals { | |
for in >= val { | |
in -= val | |
out += chars[i] | |
} | |
} | |
return | |
} | |
func main() { | |
flag.Parse() | |
if *from != "" { | |
val := fromRoman(*from) | |
fmt.Printf("FROM: %v, INT: %v", *from, val) | |
} | |
if *to > 0 { | |
roman := toRoman(*to) | |
fmt.Printf("TO: %v, ROMAN: %v", *to, roman) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment