Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
public class Solution {
public String intToRoman(int num) {
String[][] base = new String[][]{
{"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
{"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"M", "MM", "MMM", "", "", "", "", "", ""}
};
String result = "";
for(int i = 0; num != 0; num /= 10,i++){
if(num % 10 != 0) result = base[i][num%10 -1] +result;
}
return result;
}
}
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
import java.util.HashMap;
public class Solution {
public int romanToInt(String s) {
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
int result = map.get(s.charAt(0));
for(int i = 1; i < s.length(); i++){
if(map.get(s.charAt(i)) > map.get(s.charAt(i-1))) result += map.get(s.charAt(i)) - 2*map.get(s.charAt(i-1));
// MCM: 1000+100+1000-2*100 = 1900
else result += map.get(s.charAt(i));
}
return result;
}
}