This file contains 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. | |
import java.util.*; | |
public class Solution { | |
public int romanToInt(String s) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
Hashtable<Character, Integer> ht=new Hashtable<Character, Integer>(); | |
ht.put('I',1); | |
ht.put('V',5); | |
ht.put('X',10); | |
ht.put('L',50); | |
ht.put('C',100); | |
ht.put('D', 500); | |
ht.put('M',1000); | |
int n=s.length(); | |
int sum=ht.get(s.charAt(n-1)); | |
for(int i=n-2; i>=0; i--){ | |
if (ht.get(s.charAt(i+1))>ht.get(s.charAt(i))){ | |
sum=sum-ht.get(s.charAt(i)); | |
} | |
else if (ht.get(s.charAt(i+1))<=ht.get(s.charAt(i))){ | |
sum=sum+ht.get(s.charAt(i)); | |
} | |
} | |
return sum; | |
} | |
} |
No comments:
Post a Comment