Problem I: Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
解决思路
1. 将字符和整数存入map中;
2. 从后往前扫描,如果当前字符代表的值大于后一个字符的值,则用当前的值减去之前累计的值。e.g. "IV" -> 5 - 1 = 4
程序
public class Solution {
public int romanToInt(String s) {
if (s == null || s.length() == 0) {
return 0;
}
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
hm.put('I', 1);
hm.put('V', 5);
hm.put('X', 10);
hm.put('L', 50);
hm.put('C', 100);
hm.put('D', 500);
hm.put('M', 1000);
int len = s.length();
int sum = hm.get(s.charAt(len - 1));
for (int i = len - 2; i >= 0; i--) {
char cur = s.charAt(i);
char aft = s.charAt(i + 1);
if (hm.get(cur) < hm.get(aft)) {
sum -= hm.get(cur);
} else {
sum += hm.get(cur);
}
}
return sum;
}
}
Problem II: Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
解决思路
1. 存一个数字到字符的映射表,数字从大到小,包含{1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1};
2. 贪心原则,得到对应的字符串。
程序
public class Solution {
public String intToRoman(int num) {
String res = "";
if (num <= 0) {
return res;
}
int[] nums = {1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1};
String[] symbols = {"M", "CM", "D", "CD", "C", "XC",
"L", "XL", "X", "IX", "V", "IV", "I"};
int i = 0;
while (num > 0) {
int j = num / nums[i];
num -= j * nums[i];
for ( ; j > 0; j--) {
res += symbols[i];
}
++i;
}
return res;
}
}