Roman Number to Integer
Question – Given a string in roman no format (s) your task is to convert it to an integer. Various symbols and their values are given below.
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Example
Give Input: s = V Expected Output: 5
Logic
- Create a Hashmpa to store corresponding values
- Iterate over the string and compare the current character with the next one, so it’s greater than adding it to the sum otherwise need to subtract it.
- The last character is let un touched so we are adding in the last.
- Finally, return the sum.
Code
class Solution { public int romanToDecimal(String str) { // code here HashMap<Character,Integer>hm=new HashMap<>(); 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); char arr[]=str.toCharArray(); int sum=0; for(int i=0;i<arr.length-1;i++){ if(hm.get(arr[i])>=hm.get(arr[i+1])){ sum+=hm.get(arr[i]); }else{ sum-=hm.get(arr[i]); } } sum+=hm.get(arr[arr.length-1]); return sum; } }