Java Solution using Switch case


  • 0
    V

    class Solution {
    public int romanToInt(String s) {
    int sum=0;
    Boolean flag[]=new Boolean[s.length()];
    for(int i=0;i<s.length();i++)
    {
    char c=s.charAt(i);
    if(flag[i]==null || flag[i]!=true)
    {
    switch(c)
    {
    case 'M': sum=sum+1000;
    flag[i]=true;
    break;
    case 'C': if((i+1)<s.length() &&s.charAt(i+1)=='M')
    {
    sum=sum+900;
    flag[i+1]=true;
    }
    else if((i+1)<s.length() &&s.charAt(i+1)=='D')
    {
    sum=sum+400;
    flag[i+1]=true;
    }
    else
    {
    sum=sum+100;
    }
    flag[i]=true;
    break;
    case 'D': sum=sum+500;
    flag[i]=true;
    break;
    case 'X': if((i+1)<s.length() &&s.charAt(i+1)=='C')
    {
    sum=sum+90;
    flag[i+1]=true;
    }
    else if((i+1)<s.length() &&s.charAt(i+1)=='L')
    {
    sum=sum+40;
    flag[i+1]=true;
    }
    else
    {
    sum=sum+10;
    }
    flag[i]=true;
    break;
    case 'L': sum=sum+50;
    flag[i]=true;
    break;
    case 'I': if((i+1)<s.length() &&s.charAt(i+1)=='X')
    {
    sum=sum+9;
    flag[i+1]=true;
    }
    else if((i+1)<s.length() &&s.charAt(i+1)=='V')
    {
    sum=sum+4;
    flag[i+1]=true;
    }
    else
    {
    sum=sum+1;
    }
    flag[i]=true;
    break;
    case 'V': sum=sum+5;
    flag[i]=true;
    break;
    }
    }

        }
         return sum;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.