My simple Java solution


  • 0
    H

    '''
    public String intToRoman(int num) {
    StringBuilder res = new StringBuilder();
    int i = 0;
    int n = num;
    Map<Integer, String> map = new HashMap<>();
    map.put(1,"I");
    map.put(4, "IV");
    map.put(5, "V");
    map.put(9, "IX");
    map.put(10, "X");
    map.put(40, "XL");
    map.put(50, "L");
    map.put(90, "XC");
    map.put(100, "C");
    map.put(400, "CD");
    map.put(500, "D");
    map.put(900, "CM");
    map.put(1000, "M");

        num = n / 1000;
        if(num != 0){
            for(i = 0; i < num; i++)
                res.append("M");
            
        }
        num = n %1000;
        num = num / 100;
        if(num == 1 || num == 4 || num == 5 || num == 9 )
            res.append(map.get(num*100));
        else if(num < 4){
            for(i = 0; i < num; i++)
                res.append("C");
        }
        else if(num > 5 && num < 9){
            res.append("D");
            for(i = 0; i < num - 5; i++)
                res.append("C");
        }
        num = n % 100;
        num = num / 10;
        if(num == 1 || num == 4 || num == 5 || num == 9 )
            res.append(map.get(num*10));
        else if(num < 4){
            for(i = 0; i < num; i++)
                res.append("X");
        }
        else if(num > 5 && num < 9){
            res.append("L");
            for(i = 0; i < num - 5; i++)
                res.append("X");
        }
        num = n % 10;
        if(num == 1 || num == 4 || num == 5 || num == 9 )
             res.append(map.get(num));
        else if(num < 4){
            for(i = 0; i < num; i++)
                res.append("I");
        }
        else if(num > 5 && num < 9){
            res.append("V");
            for(i = 0; i < num - 5; i++)
                res.append("I");
        }
        return res.toString();
    }
    

    '''


Log in to reply
 

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