標籤:java leetcode hashmap
問題
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Tags: Math, String
代碼
public class Solution { public int romanToInt(String s) { Map<Character, Integer> map = new HashMap<Character, Integer>(); 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); int result = 0; int len = s.length(); for (int i = 0; i < len - 1; i++) { char c = s.charAt(i); int add = map.get(c); switch (c) {//參考文章下面說明中的計算規則 case ‘I‘: if (s.charAt(i + 1) == ‘V‘ || s.charAt(i + 1) == ‘X‘) result -= add; else result += add; break; case ‘X‘: if (s.charAt(i + 1) == ‘L‘ || s.charAt(i + 1) == ‘C‘) result -= add; else result += add; break; case ‘C‘: if (s.charAt(i + 1) == ‘D‘ || s.charAt(i + 1) == ‘M‘) result -= add; else result += add; break; case ‘V‘: case ‘L‘: case ‘D‘: case ‘M‘: result += add; break; default: break; } } return result + map.get(s.charAt(len - 1)); }}
已耗用時間
說明
羅馬數位計算規則,參考如下幾點:
基底字元
(‘I’, 1) (‘V’, 5) (‘X’, 10) (‘L’, 50) (‘C’, 100) (‘D’, 500) (‘M’, 1000)
1、相同的數字連寫,所表示的數等於這些數字相加得到的數,如:Ⅲ = 3;
2、小的數字在大的數位右邊,所表示的數等於這些數字相加得到的數, 如:Ⅷ = 8;Ⅻ = 12;
3、小的數字,(限於Ⅰ、X 和C)在大的數位左邊,所表示的數等於大數減小數得到的數,如:Ⅳ= 4;Ⅸ= 9;
4、V 和X 左邊的小數字只能用Ⅰ。
5、L 和C 左邊的小數字只能用X。
6、D 和M 左邊的小數字只能用C。
連結:羅馬數字 百度百科
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
LeetCode #13 Roman to Integer #Java