Are there other options?


  • 0
    string intToRoman(int num)
    {
    	string result("");
    	char *less5 = "III";
    	char *larger5 = "V";
    	char *next = "X";
    	int multi = 1;
    	while (num != 0)
    	{
    		switch (multi)
    		{
    		case 10:
    			less5 = "XXX";
    			larger5 = "L";
    			next = "C";
    			break;
    		case 100:
    			less5 = "CCC";
    			larger5 = "D";
    			next = "M";
    			break;
    		case 1000:
    			less5 = "MMM";
    			break;
    		}
    		switch (num % 10)
    		{
    		case 1:
    			result.insert(0, less5, 1);
    			break;
    		case 2:
    			result.insert(0, less5, 2);
    			break;
    		case 3:
    			result.insert(0, less5, 3);
    			break;
    		case 4:
    			result.insert(0, larger5);
    			result.insert(0, less5, 1);
    			break;
    		case 5:
    			result.insert(0, larger5);
    			break;
    		case 6:
    			result.insert(0, less5, 1);
    			result.insert(0, larger5);
    			break;
    		case 7:
    			result.insert(0, less5, 2);
    			result.insert(0, larger5);
    			break;
    		case 8:
    			result.insert(0, less5, 3);
    			result.insert(0, larger5);
    			break;
    		case 9:
    			result.insert(0, next);
    			result.insert(0, less5, 1);
    		}
    		num /= 10;
    		multi *= 10;
    	}
    	return result;
    }

  • 2

    it's kind of Greedy thinking: keep minus the biggest value until ns[i] > num, then iterate the second largest number... to the smallest number.

    public class Solution {
        public String intToRoman(int num) {        
            String[] cs = new String[] {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
            int[] ns = new int[] {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
            
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < ns.length; i++) {
                while (num >= ns[i]) {
                    num -= ns[i];
                    sb.append(cs[i]);
                }
            }
            return sb.toString();
        }
    }

  • 0
    A

    I was thinkin the same thing, get the special case and do the rest itself. But I guess the general approach is way simpler and better time complexity.


Log in to reply
 

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