Java solution


  • 0
    S

    My solution.

    public String intToRoman(int num) {
        String result = "";
    	String[] romans = {"I","V","X","L","C","D","M"};
    	int index = 0;
    	while (num > 0) {
    		int temp = num % 10;
    		switch (temp) {
    		case 1:
    			result = romans[index] + result;
    			break;
    		case 2: 
    			result = romans[index] + romans[index] + result;
    			break;
    		case 3:
    			result = romans[index] + romans[index] + romans[index] + result;
    			break;
    		case 4:
    			result = romans[index] + romans[index + 1] + result;
    			break;
    		case 5:
    			result = romans[index + 1] + result;
    			break;
    		case 6: 
    			result = romans[index + 1] + romans[index] + result;
    			break;
    		case 7:
    			result = romans[index + 1] + romans[index] + romans[index] + result;
    			break;
    		case 8:
    			result = romans[index + 1] + romans[index] + romans[index] + romans[index] + result;
    			break;
    		case 9:
    			result = romans[index] + romans[index + 2] + result;
    			break;
    		default:	
    		}
    		num = num / 10;
    		index = index + 2;
    	}
    	return result;
    }

Log in to reply
 

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