将罗马字母的字符串转换为表明的整数
Roman numerals are usually written largest to smallest from left to right. However, there are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
这题不难,用一个HashMap存罗马数字和具体数字的对应关系,而后遍历先后两两比较,该加加,该减减指针
public static int romanToInt(String s) { int num = 0; int n = s.length(); for (int i = 0; i < n-1; i++) { int curr = map(s.charAt(i)); //这里map是本身写的一个方法,里面用一个switch,至关于HashMap存对应 int next = map(s.charAt(i+1)); num = curr < next ? num - curr : num + curr; //当时一直想着用一个temp来存减的值,因此无法用for就用了while&point指针,但其实就是很简单的比后面小的话在总值里面减去就能够,不须要temp } num += map(s.charAt(n-1)); return num; }