Solution


  • 0
    F
        public String intToRoman(int num) {
            StringBuilder sb=new StringBuilder();
            int count=0;
            while(num>0){
                count++;
                int x=num%10;
                if(x==4){
                    switch(count){
                        case 1:sb.append("VI"); break;
                        case 2:sb.append("LX"); break;
                        case 3:sb.append("DC"); break;
                    }
                }
                else if(x==9){
                    switch(count){
                        case 1:sb.append("XI"); break;
                        case 2:sb.append("CX"); break;
                        case 3:sb.append("MC"); break;
                    }
                }
                else{
                    int m=x<4?x:x-5;
                    for(int i=0;i<m;i++){
                        switch(count){
                            case 1:sb.append("I"); break;
                            case 2:sb.append("X"); break;
                            case 3:sb.append("C"); break;
                            case 4:sb.append("M"); break;
                        }
                    }
                    if(x>=5){
                        switch(count){
                            case 1:sb.append("V"); break;
                            case 2:sb.append("L"); break;
                            case 3:sb.append("D"); break;
                        }
                    }
                }
                num=num/10;
            }
            return sb.reverse().toString();
        }    
    }```

Log in to reply
 

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