Java solution that not hard code the possible situation


  • 0
    Z

    generate the Roman using a chain.

    public String intToRoman(int num) {
        StringBuilder sb = new StringBuilder();
    
        int remain = num;
        remain = handle(sb, remain, 1000, "M", 100, "C");
        remain = handle(sb, remain, 500, "D", 100, "C");
        remain = handle(sb, remain, 100, "C", 10, "X");
        remain = handle(sb, remain, 50, "L", 10, "X");
        remain = handle(sb, remain, 10, "X", 1, "I");
        remain = handle(sb, remain, 5, "V", 1, "I");
        handle(sb, remain, 1, "I", 0, "");
        return sb.toString();
    }
    
    private int handle(StringBuilder sb, int num, int div, String sign, int subDiv, String subSign) {
        int factor;
        int remainder;
        int temp = div - subDiv;
        if (num >= temp) {
            factor = num / div;
            remainder = num % div;
            for (int i = 0; i < factor; i++) {
                sb.append(sign);
            }
            if (remainder >= temp) {
                sb.append(subSign).append(sign);
                remainder -= temp;
            }
            return remainder;
        }
        return num;
    }

Log in to reply
 

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