Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question
package leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* 1------I
* 5------V
* 10-----X
* 50-----L
* 100----C
* 500----D
* 1000---M
*
* @author Mouse
*
*/
public class Solution {
public static int romanToInt(String s) {
Map<String, Integer> map = new HashMap<>();
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 = 0;
if (s.length() < 0)
return 0;
if (s.length() == 1) {
return map.get(s);
}
result=(int)map.get(String.valueOf(s.charAt(0)));
for (int i = 1; i < s.length(); i++) {
int num1 = (int)map.get(String.valueOf(s.charAt(i-1)));// 前面
int num2 = (int)map.get(String.valueOf(s.charAt(i)));// 后面
if (num1<num2) {
result += num2 - 2 *num1; //前面被加过一次,故一共需要减去2个num1
}else{
result += num2;
}
}
return result;
}
public static void main(String[] args) {
int s = romanToInt("MCMXCVI");
System.out.println(s);
}
}