Skip to content

Instantly share code, notes, and snippets.

@drlsdee
Created May 16, 2024 13:03
Show Gist options
  • Save drlsdee/2111d4acd41d3265766cd10237372803 to your computer and use it in GitHub Desktop.
Save drlsdee/2111d4acd41d3265766cd10237372803 to your computer and use it in GitHub Desktop.
Converts roman numbers to Int32.
function ConvertFrom-RomanNumber {
[CmdletBinding()]
[OutputType([int])]
param (
#
[Parameter(Mandatory,ValueFromPipeline,Position=0)]
[ValidatePattern('^[ivxlcdmIVXLCDM]+$')]
[string]$InputObject
)
begin {
$dictionary = @{
[char]'I' = 1
[char]'V' = 5
[char]'X' = 10
[char]'L' = 50
[char]'C' = 100
[char]'D' = 500
[char]'M' = 1000
}
}
process {
$InputObject = $InputObject.ToUpper()
[int]$valueRight = $dictionary.Item($InputObject[-1])
[int]$valueLeft = 0
[int]$result = 0
if ($InputObject.Length -eq 1) {
return $valueRight
}
$result += $valueRight
for ($i = $InputObject.Length - 2; $i -ge 0; $i--) {
$valueLeft = $dictionary.Item($InputObject[$i])
if ($valueLeft -lt $valueRight) {
$result -= $valueLeft
}
else {
$result += $valueLeft
}
$valueRight = $valueLeft
}
return $result
}
end {}
}
@drlsdee
Copy link
Author

drlsdee commented May 16, 2024

TODO: write reverse converter, from Int32 to roman

@drlsdee
Copy link
Author

drlsdee commented May 16, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment