Share my recursive solution


  • 0
    A
    public class Solution {
        String tbl = "IVXLCDM";
        private String digitToRoman(int digit, int lvl) {
            if (digit >= 10) return digitToRoman(digit/10, lvl+2) + digitToRoman(digit%10, lvl);
            if (digit == 9) return "" + tbl.charAt(lvl) + tbl.charAt(lvl+2);
            if (digit == 5) return "" + tbl.charAt(lvl+1);
            if (digit > 5) return "" + tbl.charAt(lvl+1) + digitToRoman(digit%5, lvl);
            if (digit == 4) return "" + tbl.charAt(lvl) + tbl.charAt(lvl+1);
            String str = "";
            while(digit > 0) {
                str += tbl.charAt(lvl);
                digit--;
            }
            return str;
        }
        
        public String intToRoman(int num) {
            return digitToRoman(num, 0);
        }
    }
    

Log in to reply
 

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