You can use String in java switch case statement!


  • 0
    W

    trying 2 chars to match first is a little trick

    public class Solution {
        public int romanToInt(String s) {
            int i = 0, ans = 0, x;
            int len = s.length();
            s = s + "$"; // avoid s.substring(i, i+2) out of index
            while (i < len) {
                if ((x = r2i(s.substring(i, i+2))) != 0) {
                    ans += x;
                    i += 2;
                } else {
                    ans += r2i(s.substring(i, i+1));
                    i += 1;
                }
            }
            return ans;
        }
        
        int r2i(String s) {
            switch (s) {
                case "M":
                    return 1000;
                case "CM":
                    return 900;
                case "D":
                    return 500;
                case "CD":
                    return 400;
                case "C":
                    return 100;
                case "XC":
                    return 90;
                case "L":
                    return 50;
                case "XL":
                    return 40;
                case "X":
                    return 10;
                case "IX":
                    return 9;
                case "V":
                    return 5;
                case "IV":
                    return 4;
                case "I":
                    return 1;
                default:
                    return 0;
            }
        }
    }
    

Log in to reply
 

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