JAVA----------------Easy Version To Understand!!!!


  • 20
    H
    	public static int romanToInt(String s) {
    	if (s == null || s.length() == 0)
    		return -1;
    	HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    	map.put('I', 1);
    	map.put('V', 5);
    	map.put('X', 10);
    	map.put('L', 50);
    	map.put('C', 100);
    	map.put('D', 500);
    	map.put('M', 1000);
    	int len = s.length(), result = map.get(s.charAt(len - 1));
    	for (int i = len - 2; i >= 0; i--) {
    		if (map.get(s.charAt(i)) >= map.get(s.charAt(i + 1)))
    			result += map.get(s.charAt(i));
    		else
    			result -= map.get(s.charAt(i));
    	}
    	return result;
    }

  • 0
    J

    @HelloWorld123456 This is a very nice solution. Good job! How did you come up with the idea of using HashMap() though?


  • 0
    K

    @HelloWorld123456 Can you please tell me why mine is not working for MCMXCVI ?

    class Solution {
    public int romanToInt(String s) {
    Map <Character,Integer> map=new HashMap<Character,Integer>();
    map.put('I', 1);
    map.put('V', 5);
    map.put('X', 10);
    map.put('L', 50);
    map.put('C', 100);
    map.put('D', 500);
    map.put('M', 1000);
    Character c;
    int l = s.length();
    int val,pval=1000;
    int n=0;
    for(int i=0;i<l;i++)
    {
    c=s.charAt(i);
    val=map.get(c);
    if(val<=pval)
    n+=val;
    else
    n-=val;
    pval=val;

        }
        return n;
    }
    

    }


Log in to reply
 

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