A solution applies to numbers in any range


  • 5
    Z
    public class Solution {
        public String intToRoman(int num) {
            return (romanDigit((num / 1000) % 10, "M", "XX", "XX")) + 
                   (romanDigit((num / 100) % 10, "C", "D", "M")) +
                   (romanDigit((num / 10) % 10, "X", "L", "C")) +
                   (romanDigit(num % 10, "I", "V", "X"));
        }
        
        public String romanDigit(int n, String onechar, String fivechar, String tenchar) {
            if (n == 0) return "";
            if (n == 1) return onechar;
            if (n == 2) return onechar + onechar;
            if (n == 3) return onechar + onechar + onechar;
            if (n == 4) return onechar + fivechar;
            if (n == 5) return fivechar;
            if (n == 6) return fivechar + onechar;
            if (n == 7) return fivechar + onechar + onechar;
            if (n == 8) return fivechar + onechar + onechar + onechar;
            if (n == 9) return onechar + tenchar;
            
            return null;
        }
    }
    

    I know the listing way is not so good, but just realized that the patterns are the same and can be summarized as "onechar", "fivechar" and "tenchar", which will simplify the solution a little bit.


Log in to reply
 

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