- quite straightforward by dividing number by pre-defined divisors, then creating roman string with quotient
- tricky part is how to handle 40/90/400/900 and so on
Original code: this failed to handle special case
public class Solution {
public String intToRoman(int num) {
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "I");
map.put(5, "V");
map.put(10,"X");
map.put(50,"L");
map.put(100,"C");
map.put(500,"D");
map.put(1000,"M");
int[] dividers = new int[]{1000,500,100,50,10,5,1};
int index = 0;
int remains = 0;
int result = 0;
StringBuilder sb = new StringBuilder();
while (num >= 1)
{
int divider = dividers[index];
remains = num % divider;
result = num / divider;
if (result > 0)
{
for (int i = 0; i < result; i++)
{
sb.append(map.get(divider));
}
num = remains;
}
index++;
}
return sb.toString();
}
}
Then added special case to handle 4/9/40/90 and so on. this time it passed. Time: 804ms
another thought is that this could be processed starting from left most end. That might be a bit more efficient
public class Solution { public String intToRoman(int num) { HashMap<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "I"); map.put(4, "IV"); map.put(5, "V"); map.put(9, "IX"); map.put(10,"X"); map.put(40, "XL"); map.put(50,"L"); map.put(90, "XC"); map.put(100,"C"); map.put(400, "CD"); map.put(500,"D"); map.put(900, "CM"); map.put(1000,"M"); int[] dividers = new int[]{1000,900,500,400,100,90,50,40,10,9,5,4,1}; int index = 0; int remains = 0; int result = 0; StringBuilder sb = new StringBuilder(); while (num >= 1) { int divider = dividers[index]; remains = num % divider; result = num / divider; for (int i = 0; i < result; i++) { sb.append(map.get(divider)); } num = remains; index++; } return sb.toString(); } }