Created
May 16, 2024 13:03
-
-
Save drlsdee/2111d4acd41d3265766cd10237372803 to your computer and use it in GitHub Desktop.
Converts roman numbers to Int32.
This file contains 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
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 {} | |
} |
TODO: write reverse converter, from Int32 to roman
Useful article: https://englishhistory.net/romans/roman-numerals/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage:
Inspired by this test task: https://telegra.ph/Konverter-rimskih-chisel-05-15