Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package com.example.roman;
/**
* Created by danielvaughan on 09/10/2014.
*/
public class Roman {
public String fromArabic(int i) {
if(i == 0)
throw new IllegalArgumentException("Zero not allowed");
StringBuilder romanStr = new StringBuilder();
RomanSymbol[] symbols = RomanSymbol.values();
while(i > 0) {
int enumIndex = 0;
for (RomanSymbol symbol : symbols) {
int factor = (int) Math.floor(i / symbol.arabicValue);
if(factor > 3) {
romanStr.append(symbol.romanValue).append(symbols[enumIndex-1].romanValue);
i-= (factor * symbol.arabicValue);
break;
} else if (factor > 0 && factor <= 3){
romanStr.append(symbol.romanValue);
i -= symbol.arabicValue;
break;
}
enumIndex++;
}
}
return romanStr.toString();
}
private enum RomanSymbol {
THOUSAND(1000, "M"),
FIVE_HUNDRED(500, "D"),
HUNDRED(100, "C"),
FIFTY(50, "L"),
TEN(10, "X"),
FIVE(5, "V"),
ONE(1, "I");
int arabicValue;
String romanValue;
RomanSymbol(int arabicValue, String romanValue) {
this.arabicValue = arabicValue;
this.romanValue = romanValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment