Easiest Java Solution


  • 2
    S

    public class Solution {

    public String intToRoman(int num) {
        if(num==0) return "";
        if(num>=1000) return "M"+intToRoman(num-1000);
        if(num>=900) return "CM"+intToRoman(num-900);
        if(num>=500) return "D"+intToRoman(num-500);
        if(num>=400) return "CD"+intToRoman(num-400);
        if(num>=100) return "C"+intToRoman(num-100);
        if(num>=90) return "XC"+intToRoman(num-90);
        if(num>=50) return "L"+intToRoman(num-50);
        if(num>=40) return "XL"+intToRoman(num-40);
        if(num>=10) return "X"+intToRoman(num-10);
        if(num>=9) return "IX"+intToRoman(num-9);
        if(num>=5) return "V"+intToRoman(num-5);
        if(num>=4) return "IV"+intToRoman(num-4);
        if(num>=1) return "I"+intToRoman(num-1);
        return "";
    }
    

    }


  • 0
    A

    I still can not submit solutions (I get failures) so I will post it here:

    Yet one more Java solution:

    public class IntToRoman {

    public static String giveTen(int num, char ones, char fives, char tens) {
        switch (num) {
            case 0: return "";
            case 1: return "" + ones;
            case 2: return "" + ones + ones;
            case 3: return "" + ones + ones + ones;
            case 4: return "" + ones + fives;
            case 5: return "" + fives;
            case 6: return "" + fives + ones;
            case 7: return "" + fives + ones + ones;
            case 8: return "" + fives + ones + ones + ones;
            case 9: return "" + ones + tens;
        }
        return "";
    }
    
    static String IntToRoman(int num) {
        String result;
        result = giveTen(num % 10, 'I', 'V','X');
        num = num / 10;
        result = giveTen(num % 10, 'X', 'L','C') +  result;
        num = num / 10;
        result = giveTen(num % 10, 'C', 'D','M') + result;
        return result;
    }
    
    public static void main(String[] args) {
        System.out.println(IntToRoman(455));
    }
    

    }


Log in to reply
 

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