Solution to Problem 12 Integer to Roman


  • 0
    S

    The idea is to get the largest remaining value of the integer that can be represented by one or two letters of Roman. For example, 1000 can be represented by "M", 900 can be represented by "CM", 500 can be represented by "D", 400 can be represented by "CD", 100 can be represented by "C", etc. Once such a remaining value is found, the value is subtracted from the integer, and the corresponding letters are concatenated to the Roman representation.
    When the integer value becomes 0, the Roman is finished.

    public class Solution {
    	public String intToRoman(int num) {
    		int[] values = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    		int length = values.length;
    		int index = 0;
    		String roman = "";
    		while (num > 0 && index < length) {
    			int current = values[index];
    			int count = num / current;
    			if (count > 0) {
    				String currentStr = getRoman(current);
    				for (int i = 0; i < count; i++)
    					roman += currentStr;
    				num = num % current;
    			}
    			index++;
    		}
    		return roman;
    	}
    
    	public String getRoman(int num) {
    		switch (num) {
    		case 1000:
    			return "M";
    		case 900:
    			return "CM";
    		case 500:
    			return "D";
    		case 400:
    			return "CD";
    		case 100:
    			return "C";
    		case 90:
    			return "XC";
    		case 50:
    			return "L";
    		case 40:
    			return "XL";
    		case 10:
    			return "X";
    		case 9:
    			return "IX";
    		case 5:
    			return "V";
    		case 4:
    			return "IV";
    		case 1:
    			return "I";
    		default:
    			return "";
    		}
    	}
    }
    

Log in to reply
 

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