Skip to content

Instantly share code, notes, and snippets.

@sahirshahryar
Last active March 31, 2023 04:12
Show Gist options
  • Save sahirshahryar/7739405 to your computer and use it in GitHub Desktop.
Save sahirshahryar/7739405 to your computer and use it in GitHub Desktop.
Roman numeral conversion
public static String romanNumerals (int value) {
String[] values = {
"M", "CM", "D", "CD", "C", "XC",
"L", "XL", "X", "IX", "V", "IV", "I"
};
int[] correspondents = {
1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < values.length; ++i) {
while (value >= correspondents[i]) {
result.append(values[i]);
value -= correspondents[i];
}
}
return result.toString();
}
public static String romanNumerals (int value) {
// Example unit: 1792 (MDCCXCII)
StringBuilder result = new StringBuilder();
while (value >= 1000) { // Append M, value = 792
result.append('M');
value -= 1000;
}
while (value >= 900) {
result.append("CM");
value -= 900;
}
while (value >= 500) { // Append D, value = 292
result.append('D');
value -= 500;
}
while (value >= 400) {
result.append("CD");
value -= 400;
}
while (value >= 100) { // Append CC, value = 92
result.append('C');
value -= 100;
}
while (value >= 90) { // Append XC, value = 2
result.append("XC");
value -= 90;
}
while (value >= 50) {
result.append('L');
value -= 50;
}
while (value >= 40) {
result.append("XL");
value -= 40;
}
while (value >= 10) {
result.append('X');
value -= 10;
}
while (value >= 9) {
result.append("IX");
value -= 9;
}
while (value >= 5) {
result.append('V');
value -= 9;
}
while (value >= 4) {
result.append("IV");
value -= 4;
}
while (value >= 1) { // Append II, value = 0
result.append('I');
--value;
}
return result.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment