Created
December 27, 2013 09:18
-
-
Save wayetan/8144518 to your computer and use it in GitHub Desktop.
Roman to Integer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Given a roman numeral, convert it to an integer. | |
| * Input is guaranteed to be within the range from 1 to 3999. | |
| */ | |
| public class Solution { | |
| public int romanToInt(String s) { | |
| HashMap<Character, Integer> dic = new HashMap<Character, Integer>(); | |
| dic.put('I', 1); | |
| dic.put('V', 5); | |
| dic.put('X', 10); | |
| dic.put('L', 50); | |
| dic.put('C', 100); | |
| dic.put('D', 500); | |
| dic.put('M', 1000); | |
| //start from the rightmost one. | |
| int res = dic.get(s.charAt(s.length() - 1)); | |
| for(int i = s.length() - 2; i >= 0; i--){ | |
| if(dic.get(s.charAt(i + 1)) <= dic.get(s.charAt(i))) | |
| res += dic.get(s.charAt(i)); | |
| else | |
| res -= dic.get(s.charAt(i)); | |
| } | |
| return res; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment