My Java Solution


  • 0
    L
    public String intToRoman(int num) {
        //Reference: http://en.wikipedia.org/wiki/Roman_numerals
        StringBuilder sb = new StringBuilder();
        int current = num;
        for(int i = 3; i >=0; i--){
            int digit = (int) Math.pow(10, i);
            int count = current/digit;
            transfer(i, count, sb);
            current = current % digit;
        }
        return sb.toString();
    }
    
    private void transfer(int i, int count, StringBuilder sb){
        char[] roman= new char[]{'I','V','X','L','C','D','M'};
        int index = i*2;
        if(count == 0){
            return;
        }if(count > 0 && count <= 3){
            while(count-- >0){
                sb.append(roman[index]);
            }
        } else if(count == 4){
            sb.append(roman[index]);
            sb.append(roman[index + 1]);
        } else if(count < 9){
            sb.append(roman[index + 1]);
            count = count - 5;
            while(count-- >0){
                sb.append(roman[index]);
            }
        } else{
            sb.append(roman[index]);
            sb.append(roman[index + 2]);
        }
    }

Log in to reply
 

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