Roman To Integer With and Without solution


#1

Using HashMap
public class Solution
{
public int romanToInt(String s)
{
if(s.length()==0)
{
return 0;
}

    HashMap<Character,Integer> m=new HashMap<Character,Integer>();
    
    m.put('I',1);
    m.put('V',5);
    m.put('X',10);
    m.put('L',50);
    m.put('C',100);
    m.put('D',500);
    m.put('M',1000);
    
    int result=0;
    for(int i=0;i<s.length();i++)
    {
        if(i>0 && m.get(s.charAt(i))>m.get(s.charAt(i-1)))
        {
            result=result+ (m.get(s.charAt(i))- 2*m.get(s.charAt(i-1)));
        }
        else
        {
            result=result+m.get(s.charAt(i));
        }
    }
    return result;
}

}

Without HashMap

public class Solution
{

int value(char c)
{
    switch(c)
    {
        case 'I':
            return 1;
        case 'V':
            return 5;
        case 'X':
            return 10;
        case 'L':
            return 50;
        case 'C':
            return 100;
        case 'D':
            return 500;
        case 'M':
            return 1000;
        default:
            return 0;
    }
}

public int romanToInt(String s)
{
    if(s.length()==0)
    {
        return 0;
    }
    int result=0;
    for(int i=0;i<s.length();i++)
    {
        if(i>0 && value(s.charAt(i))>value(s.charAt(i-1)))
        {
            result=result+(value(s.charAt(i))-2*value(s.charAt(i-1)));
        }
        else
        {
            result=result+value(s.charAt(i));
        }
    }
    return result;
}

}