T13 罗马数字转整数

tech2025-08-13  10

思想:先建立那几个基准字符与对应数字之间的映射,然后之后就抓住一点即可:如果当前字符表示的数字比下一个字符表示的数字小,则令res-=当前字符表示的数字,否则令res+=当前字符表示的数字

class Solution { public int romanToInt(String s) { int len = s.length(); if(len<=0)return 0; Map<Character,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); if(len==1){ return map.get(s.charAt(0)); } int res = 0; for(int i=0;i<len;i++){ int curNum = map.get(s.charAt(i)); int nexNum = (i+1<len)?map.get(s.charAt(i+1)):Integer.MIN_VALUE; if(curNum<nexNum){ res-=curNum; }else{ res+=curNum; } } return res; } }
最新回复(0)