Created
October 10, 2014 08:47
-
-
Save danielvaughan/5bf4430a2a4c64313e2a to your computer and use it in GitHub Desktop.
This file contains 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
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