1ms Java solution


  • 0
    S
    public class Solution {
        public int romanToInt(String s) {
            HashMap<String, Integer> hashMap = new HashMap<>();
            int newNum[] = new int[s.length()];
            int sum = 0;
            String string = new String();
            hashMap.put("I", 1);
            hashMap.put("V", 5);
            hashMap.put("X", 10);
            hashMap.put("L", 50);
            hashMap.put("C", 100);
            hashMap.put("D", 500);
            hashMap.put("M", 1000);
            for (int i = 0; i < s.length(); i++) {
                string = String.valueOf(s.charAt(i));
                newNum[i] = hashMap.get(string);
            }
            sum += newNum[s.length() - 1];
            for (int j = s.length() - 1; j > 0; j--) {
                if(newNum[j - 1] >= newNum[j]) {sum += newNum[j - 1];}
                else {sum -= newNum[j - 1];}
            }
            return sum;
        }
    }

Log in to reply
 

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