Java Solution


  • 0
    S

    class Solution {
    public int romanToInt(String s) {
    int num = 0;
    for(int i = 0; i < s.length(); i++){
    if(i+1 < s.length()){
    if(value(s.charAt(i)) < value(s.charAt(i+1))){
    num += value(s.charAt(i+1)) - value(s.charAt(i));
    i++;
    }else{
    num += value(s.charAt(i));
    }
    }else{
    num += value(s.charAt(i));
    }
    }
    System.out.println(num);
    return num;
    }

    public int value(char r){
        if (r == 'I')
            return 1;
        if (r == 'V')
            return 5;
        if (r == 'X')
            return 10;
        if (r == 'L')
            return 50;
        if (r == 'C')
            return 100;
        if (r == 'D')
            return 500;
        if (r == 'M')
            return 1000;
        return -1;
    }
    

    }


Log in to reply
 

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