Roman to Integer

来源:互联网 发布:淘宝 发票 搜索什么 编辑:程序博客网 时间:2024/05/22 12:46

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.


import java.util.HashMap;public class Solution {public int romanToInt(String s) {int length = s.length();if (s == null || length == 0) {return 0;}HashMap<Character, Integer> hm = new HashMap<Character, Integer>();hm.put('I', 1);hm.put('V', 5);hm.put('X', 10);hm.put('L', 50);hm.put('C', 100);hm.put('D', 500);hm.put('M', 1000);int pre = 10000;int res = 0;int cur = 0;for (int i = 0; i < length; i++) {cur = hm.get(s.charAt(i));res += cur;if (cur > pre) {res -= 2 * pre;}pre = cur;}return res;}}


0 0
原创粉丝点击