原题链接:13.罗马数字转整数

题目描述:

image.png


解:

观察规律,罗马数字小值在大值右边时,直接加上这个值,如果在左边,就加上他的相反数。

  1. class Solution {
  2. public int romanToInt(String s) {
  3. HashMap<Character, Integer> map = new HashMap<>();
  4. map.put('I',1);
  5. map.put('V',5);
  6. map.put('X',10);
  7. map.put('L',50);
  8. map.put('C',100);
  9. map.put('D',500);
  10. map.put('M',1000);
  11. int ret = 0;
  12. for(int i=0; i<s.length(); i++) {
  13. if ( i!=s.length()-1 && map.get(s.charAt(i)) < map.get(s.charAt(i+1))) {
  14. ret += -1 * map.get(s.charAt(i));
  15. } else {
  16. ret += map.get(s.charAt(i));
  17. }
  18. }
  19. return ret;
  20. }
  21. }