Skip to content

Instantly share code, notes, and snippets.

@sanitz
Created June 28, 2011 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sanitz/1051813 to your computer and use it in GitHub Desktop.
Save sanitz/1051813 to your computer and use it in GitHub Desktop.
Result of the roman numbers kata in Java
package kata;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
public class RomanNumbersTest {
static class Roman {
final int decimal;
final String roman;
public Roman(int decimal, String roman) {
this.decimal = decimal;
this.roman = roman;
}
}
static Roman one = new Roman(1, "I");
static Roman four = new Roman(4, "IV");
static Roman five = new Roman(5, "V");
static Roman nine = new Roman(9, "IX");
static Roman ten = new Roman(10, "X");
static Roman fourty = new Roman(40, "XL");
static Roman fifty = new Roman(50, "L");
static Roman ninety = new Roman(90, "XC");
static Roman hundred = new Roman(100, "C");
static List<Roman> numbers = Arrays.asList(hundred, ninety, fifty, fourty, ten,
nine, five, four, one);
static String toRoman(int n) {
String result = "";
for (Roman num : numbers) {
while (n >= num.decimal) {
result += num.roman;
n -= num.decimal;
}
}
return result;
}
@Test
public void testSimpleNumbers() {
assertEquals("I", toRoman(1));
assertEquals("II", toRoman(2));
assertEquals("III", toRoman(3));
assertEquals("IV", toRoman(4));
assertEquals("V", toRoman(5));
assertEquals("VI", toRoman(6));
assertEquals("VII", toRoman(7));
assertEquals("XXIII", toRoman(23));
assertEquals("LV", toRoman(55));
assertEquals("XLII", toRoman(42));
assertEquals("XCIX", toRoman(99));
assertEquals("CXI", toRoman(111));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment