Recursive solution

  • 0

    class Solution {
    public String intToRoman(int num) {
    Map<Integer, String> baseCase = new HashMap<>();
    baseCase.put(1, "I");
    baseCase.put(2, "II");
    baseCase.put(3, "III");
    baseCase.put(4, "IV");
    baseCase.put(5, "V");
    baseCase.put(6, "VI");
    baseCase.put(7, "VII");
    baseCase.put(8, "VIII");
    baseCase.put(9, "IX");
    Map<Character, Character> recursiveMap = new HashMap<>();
    recursiveMap.put('I', 'X');
    recursiveMap.put('X', 'C');
    recursiveMap.put('C', 'M');
    recursiveMap.put('V', 'L');
    recursiveMap.put('L', 'D');
    return intToRoman(num, baseCase, recursiveMap);

    public String intToRoman(int num, Map<Integer,String> baseCase, Map<Character, Character> recursiveMap){
        if(num == 0) return "";
        if(num > 0 && num < 10){
            return baseCase.get(num);
        String intermediateResult = intToRoman(num/10, baseCase, recursiveMap);
        //System.out.println(num + " ," + intermediateResult);
        StringBuffer intermediateResultConverted = new StringBuffer();
        for(int i=0; i<intermediateResult.length();i++){
        intermediateResultConverted.append(intToRoman(num%10, baseCase, recursiveMap));
        return intermediateResultConverted.toString();


Log in to reply

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