Leet Code Problem-Easy
Today, i am starting my journey from leetcode-easy . Here the Problem is to Convert Roman to an Integer.
Problem Link- https://leetcode.com/problems/roman-to-integer/
Approach -We have to keep the conditions in mind. When we traverse the string from left to right, we have to check that if we encounter a small value compared to the next value(i<i+1), we have to subtract the current value from a global value(It is defined globally with 0)[gloabl-=currentvalue] else addition.
Note- we have to add a condition if reach the last value of the string then the condition should be added (i<string length -1)
Here Jave Solution
class Solution {
public int romanToInt(String s) {
//map of roman value
Map<Character, Integer> rmInt=new HashMap<Character, Integer>();
rmInt.put(‘I’,1);
rmInt.put(‘V’,5);
rmInt.put(‘X’,10);
rmInt.put(‘L’,50);
rmInt.put(‘C’,100);
rmInt.put(‘D’,500);
rmInt.put(‘M’,1000);
int ans=0; //global value
for(int i=0;i<s.length();i++){
if( i<s.length()-1 && rmInt.get(s.charAt(i))<rmInt.get(s.charAt(i+1)) ) // check the value with condition
ans-=rmInt.get(s.charAt(i));
else
ans+=rmInt.get(s.charAt(i));
}
return ans; //return the current value
}
}
Input-1
s =
“III”
Output
3
Expected
3
Input-2
s =“LVIII”
Output
58
Expected
58
Input-3
s =“MCMXCIV”
Output
1994
Expected
1994