close
13. Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
這題比較難的是不知道羅馬數字和它的規則......
其實羅馬數字是用小的在大的前的話表示那是要減的
ex. XIV 10-1+5=14
1 5 10 50 100 500 1000
I V X L C D M
https://www.rapidtables.com/math/symbols/roman_numerals.html
知道這些就很好做了
這題用hashmap比較好,因為看有人討論說switch 會超時
class Solution { public int romanToInt(String s) { HashMap<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); int result=0; for(int index=0; index < s.length(); index++){ int val = map.get(s.charAt(index)); if(index+1 < s.length() && val < map.get(s.charAt(index+1))) result -= val; else result += val; } return result; } }
全站熱搜