1. Question
罗马数转为整型,输入确保在1-3999之内。相似的题目是Integer to Roman
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
2. Solution
将I:1, V:5, X:10, L:50, C:100, D:500, M:1000存储起来,依次按相加和相减规则计算即可
public class Solution { public int romanToInt(String s){ HashMap<Character,Integer> romanBase = new HashMap<Character,Integer>(); romanBase.put(‘I‘,1); romanBase.put(‘V‘,5); romanBase.put(‘X‘, 10); romanBase.put(‘L‘, 50); romanBase.put(‘C‘,100); romanBase.put(‘D‘, 500); romanBase.put(‘M‘, 1000); int res = 0; int i; for( i=0; i<s.length()-1; i++ ){ char c = s.charAt(i); int now = romanBase.get(c); int next = romanBase.get( s.charAt(i+1) ); if( now < next ){ res += ( next - now ); ++i; } else res += now; } if( i==s.length()-1 ) res += romanBase.get(s.charAt(i)); return res; } }
时间: 2024-10-05 23:26:42