My JAVA Generic Solution


  • 2
        public String intToRoman(int num) {
    		StringBuilder sb = new StringBuilder();
    		char[] romanChar = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
    		int i = 0;
    		while (num > 0 && i < romanChar.length - 1) {
    			if (num % 10 < 4) {
    				for (int j = 0; j < num % 10; j++) {
    					sb.append(romanChar[i]);
    				}
    			} else if (num % 10 == 4) {
    				sb.append(romanChar[i + 1]).append(romanChar[i]);
    			} else if (num % 10 < 9) {
    				for (int j = 5; j < num % 10; j++) {
    					sb.append(romanChar[i]);
    				}
    				sb.append(romanChar[i + 1]);
    			} else {
    				sb.append(romanChar[i + 2]).append(romanChar[i]);
    			}
    			num = num / 10;
    			i = i + 2;
    		}
    		if (num != 0) {
    			for (int j = 0; j < num % 10; j++) {
    				sb.append(romanChar[i]);
    			}
    		}
    		return sb.reverse().toString();
            }
    

  • 0
    J

    excellent solution. Good job, big monster king of mountain chicken village.


Log in to reply
 

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