Guest User

Untitled

a guest
Jul 19th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. import junit.framework.TestCase;
  2.  
  3. public class RomanNumerEncoderTest extends TestCase {
  4.  
  5. public void testEncode() {
  6. assertEncode("", 0);
  7. assertEncode("I", 1);
  8. assertEncode("II", 2);
  9. assertEncode("III", 3);
  10. assertEncode("IV", 4);
  11. assertEncode("V", 5);
  12. assertEncode("VI", 6);
  13. assertEncode("IX", 9);
  14. assertEncode("X", 10);
  15. assertEncode("XI", 11);
  16. assertEncode("XL", 40);
  17. assertEncode("L", 50);
  18. assertEncode("XC", 90);
  19. assertEncode("C", 100);
  20. assertEncode("D", 500);
  21. assertEncode("M", 1000);
  22. assertEncode("MDCCCLXXVIII", 1878);
  23. assertEncode("MCMLIII", 1953);
  24. assertEncode("MMXI", 2011);
  25. assertEncode("XCIX", 99);
  26. assertEncode("CMXC", 990);
  27. }
  28.  
  29. private void assertEncode(String numeral, int arabicNumber) {
  30. assertEquals(numeral, new RomanNumberEncoder().encode(arabicNumber));
  31. }
  32.  
  33. }
  34.  
  35. class RomanNumberEncoder {
  36.  
  37. private static final int[] decimalValueOfRomanNumeral = {
  38. 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
  39. };
  40. private static final String[] romanNumeral = {
  41. "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
  42. };
  43.  
  44. private int currentArabicRemainder;
  45. private StringBuilder romanNumeralTemp = new StringBuilder();
  46.  
  47. public String encode(int pArabicNumber) {
  48. initTemporaryMenbers(pArabicNumber);
  49. appendElementaryNumeralsAsNeeded();
  50. return encodedRomanNumeralString();
  51. }
  52.  
  53. private void initTemporaryMenbers(int pArabicNumber) {
  54. currentArabicRemainder = pArabicNumber;
  55. romanNumeralTemp = new StringBuilder();
  56. }
  57.  
  58. private void appendElementaryNumeralsAsNeeded() {
  59. for (int i = 0; isMoreElementarNumeralsNeededAndAvailable(i); i++) {
  60. appendElementaryNumeralGroupForIndex(i);
  61. }
  62. }
  63.  
  64. private boolean isMoreElementarNumeralsNeededAndAvailable(int i) {
  65. return (i < decimalValueOfRomanNumeral.length)
  66. && (0 < currentArabicRemainder);
  67. }
  68.  
  69. private void appendElementaryNumeralGroupForIndex(int pElementaryNumeralIndex) {
  70. while (currentArabicRemainder >= decimalValueOfRomanNumeral[pElementaryNumeralIndex]) {
  71. romanNumeralTemp.append(romanNumeral[pElementaryNumeralIndex]);
  72. currentArabicRemainder -= decimalValueOfRomanNumeral[pElementaryNumeralIndex];
  73. }
  74. }
  75.  
  76. private String encodedRomanNumeralString() {
  77. assert (0 == currentArabicRemainder);
  78. return this.romanNumeralTemp.toString();
  79. }
  80. }
Add Comment
Please, Sign In to add comment