符号较多,偷个懒题目和示例截图放上来
示例
一开始想用switch方法,但是又想到了hashmap于是用了hashmap
import java.util.HashMap;
public class test{
public static void main(String[] args) {
String s1="III";
String s2="IV";
String s3="IX";
String s4="LVIII";
String s5="MCMXCIV";
System.out.println(romanToInt(s1));
System.out.println(romanToInt(s2));
System.out.println(romanToInt(s3));
System.out.println(romanToInt(s4));
System.out.println(romanToInt(s5));
}
public static int romanToInt(String s) {
int count=0;
char before='1';
HashMap<Character,Integer> h=new HashMap<>();
h.put('I',1);
h.put('V',5);
h.put('X',10);
h.put('L',50);
h.put('C',100);
h.put('D',500);
h.put('M',1000);
for (int i=s.length()-1;i>=0;i--){
if (((s.charAt(i)=='I')&&(before=='V'))||((s.charAt(i)=='I')&&(before=='X'))||
((s.charAt(i)=='X')&&(before=='L'))||((s.charAt(i)=='X')&&(before=='C'))||
((s.charAt(i)=='C')&&(before=='D'))||((s.charAt(i)=='C')&&(before=='M'))
){
count-=h.get(s.charAt(i));
}else {
count+=h.get(s.charAt(i));
}
before=s.charAt(i);
}
return count;
}
}
最后得到结果
之后看了一下大家的做法如果用swich而不用hashmap得到的结果
执行用时 :4 ms, 在所有 java 提交中击败了99.93% 的用户
内存消耗 :36.1 MB, 在所有 java 提交中击败了98.73%的用户
这么看来简单的时候swich方法比hashmap要节省很多的资源