Java Readable Solution using only generic roman characters I,V,X,L,C,D,M


  • 1
    R

    public String intToRoman(int num) {

        ArrayList<Integer> digs = new ArrayList<>();
        int temp,pow=0;
        LinkedHashMap<Character, Integer> romanDig = new LinkedHashMap<>();
        romanDig.put('M', 1000);
        romanDig.put('D', 500);
        romanDig.put('C', 100);
        romanDig.put('L', 50);
        romanDig.put('X', 10);
        romanDig.put('V', 5);
        romanDig.put('I', 1);
    
        while(num > 0){
            temp = num%10;
            digs.add((int) (temp*Math.pow(10,pow)));
            pow++;
            num /= 10;
        }
        StringBuilder sb = new StringBuilder();
        for(int i = pow-1; i >= 0 ; i--){
            num = digs.get(i);
            for (Map.Entry<Character, Integer> e : romanDig.entrySet()) {
                if(num+100 == e.getValue() && num < 1000){
                    sb.append('C');
                    sb.append(e.getKey());
                    break;
                }
                if(num+10 == e.getValue() && num < 100){
                    sb.append('X');
                    sb.append(e.getKey());
                    break;
                }
                if(num+1 == e.getValue() && num < 10){
                    sb.append('I');
                    sb.append(e.getKey());
                    break;
                }
                while(e.getValue() <= num) {
                    num -= e.getValue();
                    sb.append(e.getKey());
                }
                if(num == 0)
                    break;
            }
    
        }
    
        return sb.toString();
    
    }

Log in to reply
 

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