Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Arabic to roman numerals
public class RomanNumeral {
private final HashMap<Integer, String> map = new HashMap<Integer, String>() {
{
put(1, "I");
put(5, "V");
put(10, "X");
put(50, "L");
put(100, "C");
put(500, "D");
put(1000, "M");
}
};
private final String value;
public RomanNumeral(int number) {
this.value = convert(number);
}
private String convert(int number) {
String result = "";
result = result + nTimes(map.get(1000), number/1000);
result = result + getOptimizedString((number % 1000) / 100, map.get(100), map.get(500), map.get(1000));
result = result + getOptimizedString((number % 100) / 10, map.get(10), map.get(50), map.get(100));
result = result + getOptimizedString(number % 10, map.get(1), map.get(5), map.get(10));
return result;
}
private String nTimes(String str, int n) {
return String.join("", Collections.nCopies(n, str));
}
private String getOptimizedString(int n, String lower, String middle, String upper) {
String result = "";
switch (n) {
case 1:
case 2:
case 3:
result = result + nTimes(lower, n);
break;
case 4:
result = result + lower + middle;
break;
case 5:
result = result + middle;
break;
case 6:
result = result + middle + lower;
break;
case 7:
result = result + middle + lower + lower;
break;
case 8:
result = result + middle + lower + lower + lower;
break;
case 9:
result = result + lower + upper;
break;
}
return result;
}
@Override
public String toString() {
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.