An optimal and easy solution in Java


  • 0
    F

    Hi everyone.

    I present you here an optimal version of the classical function (that you can find easliy in internet or even here) which gives the roman presentation using a static array. The idea of the optimisation is to stop when the number becomes zero. No need to iterate until the end of your values array even if your number becomes zero! Which is not optimal at all and completely useless.

    In addition to that you can also check if the input number has a valid roman representation if you want (that make the function a litllte slower but in reality, it's more realitic). It's always a good thing to check that (even if the exercice assumes that the number has it already).

    Here is my optimal function :

    public static String intToRoman(int num){
    	if (num < 1 || num > 3999) return "";
    	
    	StringBuilder result = new StringBuilder();
    	
    	String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
    	int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
    	
    	int i = 0;
    //iterate until the number becomes zero, NO NEED to go until the last element in roman array
    	while (num >0) {
    		while ( num >= values[i]) {
    			num -= values[i];
    			result.append(roman[i]);
    		}
    		i++;
    	}
    	return result.toString();
    }
    

    As you see, you add just a simple line and you win an optimisation since the code will stop if the current number becomes zero (instead of doing additionnal iterations in the roman array).


Log in to reply
 

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