Created
March 6, 2018 02:13
-
-
Save mrbusche/256c6f856edab834d55738e48c434b68 to your computer and use it in GitHub Desktop.
Number to Roman Numeral
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
String getRomanNumeral(int userEnteredNumber) { | |
//Numbers that are needed to reduce the complexity of code. | |
//In some cases the numbers are absolutely necessary (1000, 500, etc) | |
//but numbers like 990, 490 are added to decrease code complexity | |
List numbers = [1000, 999, 990, 900, 500, 499, 490, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] | |
List romanNumerals = ['M','CMXCIX','XM','CM','D','CDXCIX','XD','CD','C','XC','L','XL','X','IX','V','IV','I'] | |
String romanNumeral = '' | |
int i = 0 | |
while (userEnteredNumber > 0) { | |
while (userEnteredNumber - numbers[i] >= 0) { | |
userEnteredNumber -= numbers[i] | |
romanNumeral += romanNumerals[i] | |
} | |
i++; | |
} | |
return romanNumeral | |
} | |
println 'I' == getRomanNumeral(1) | |
println 'II' == getRomanNumeral(2) | |
println 'III' == getRomanNumeral(3) | |
println 'IV' == getRomanNumeral(4) | |
println 'V' == getRomanNumeral(5) | |
println 'VI' == getRomanNumeral(6) | |
println 'VII' == getRomanNumeral(7) | |
println 'VIII' == getRomanNumeral(8) | |
println 'IX' == getRomanNumeral(9) | |
println 'X' == getRomanNumeral(10) | |
println 'C' == getRomanNumeral(100) | |
println 'CI' == getRomanNumeral(101) | |
println 'CD' == getRomanNumeral(400) | |
println 'CDXCIX' == getRomanNumeral(499) | |
println 'XCIX' == getRomanNumeral(99) | |
println 'CCC' == getRomanNumeral(300) | |
println 'CMXCIX' == getRomanNumeral(999) | |
println 'M' == getRomanNumeral(1000) | |
println 'MM' == getRomanNumeral(2000) | |
println 'MMM' == getRomanNumeral(3000) | |
println 'MMD' == getRomanNumeral(2500) | |
println 'MMDI' == getRomanNumeral(2501) | |
println 'MMCMXCIX' == getRomanNumeral(2999) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment