My code, possibly easy to understand


  • 0
    J

    Three roman characters are put into one group for the generation of related roman number.

    string combine(string one, string five, string ten, int number)
    {
    	string roman = "";
    
    	switch (number)
    	{
    		case 0:
    		case 1:
    		case 2:
    		case 3:
    			for (int i = 0; i != number; ++i)
    			{
    				roman += one;
    			}
    			break;
    		case 4:
    			roman = one + five;
    			break;
    		case 5:
    		case 6:
    		case 7:
    		case 8:
    			roman = five;
    			for (int i = 0; i != number - 5; ++i)
    			{
    				roman += one;
    			}
    			break;
    		case 9:
    			roman = one + ten;
    			break;
    	}
    	return roman;
    }
    string intToRoman(int num)
    {
    	string roman = "";
    
    	int thousands = num / 1000;
    	for (int i = 0; i != thousands; ++i)
    	{
    		roman += "M";
    	}
    
    	
    	num = num % 1000;
    	int hundreds = num / 100;
    	roman += combine("C", "D", "M", hundreds);
    
    	num = num % 100;
    	int tens = num / 10;
    	roman += combine("X", "L", "C", tens);
    
    	num = num % 10;
    	int ones = num;
    	roman += combine("I", "V", "X", ones);
    
    	return roman;
    }

Log in to reply
 

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