13. Roman to Integer

C++ | Hash

class Solution {

public:

    int romanToInt(string s) {

unordered_map<char,int> mp;

mp['I']=1;

mp['V']=5;

mp['X']=10;

mp['L']=50;

mp['C']=100;

mp['D']=500;

mp['M']=1000;


    int sum=0;

    for(int i=0;i<s.length()-1;i++){

        if(mp[s[i]]>=mp[s[i+1]]){

            sum+=mp[s[i]];

        }

        else{

            sum-=mp[s[i]];

        }

    }

    sum+=mp[s[s.length()-1]];

    return sum;

}

};

Comments

Popular posts from this blog

1431. Kids With the Greatest Number of Candies

125. Valid Palindrome

771. Jewels and Stones