Skip to content

Instantly share code, notes, and snippets.

@danielvaughan
Created October 10, 2014 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielvaughan/5bf4430a2a4c64313e2a to your computer and use it in GitHub Desktop.
Save danielvaughan/5bf4430a2a4c64313e2a to your computer and use it in GitHub Desktop.
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