7ms java simpliest solution


  • 2
    V
    private static final int[] ints = {1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,200,300,400,500,600,700,800,900,1000};
    private static final String[] strings = {"I","II","III","IV","V","VI","VII","VIII","IX","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","M"};
    
    /*
    6 = VI
    4 = IV
    999 = CMXCIX
    900 = CM
    
    3999 = MMMCMXCIX
     */
    public String intToRoman(int num) {
    	StringBuilder result = new StringBuilder(15);
    	while (num > 0) {
    		for (int i = ints.length - 1; i >= 0; i--) {
    			if (num >= ints[i]) {
    				result.append(strings[i]);
    				num -= ints[i];
    				break;
    			}
    		}
    	}
    	return result.toString();
    }

Log in to reply
 

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