C++ solution with 30ms (but also long)


  • 0
    C

    class Solution {
    public:
    // convert from 1 to 999
    string digit2Roman(int n, int level){

    	if (level == 2 && n == 9)	return "CM"; // special cases
    	else if (n == 0)	return "";
    
    	char **a = new char*[3];
    	for (int i = 0; i < 3; i++)
    		a[i] = new char[2];
    
    	a[0][0] = 'I';
    	a[0][1] = 'V';
    	a[1][0] = 'X';
    	a[1][1] = 'L';
    	a[2][0] = 'C';
    	a[2][1] = 'D';
    
    	string result("");
    
    	switch(n){
    	case 1: result.append(1u, a[level][0]);
    			break;
    	case 2: result.append(2u, a[level][0]);
    			break;
    	case 3: result.append(3u, a[level][0]);
    			break;
    
    	case 4: result.append(1u, a[level][0]);
    			result.append(1u, a[level][1]);
    			break;
    	case 5: result.append(1u, a[level][1]);
    			break;
    	case 6: result.append(1u, a[level][1]);
    			result.append(1u, a[level][0]);
    			break;
    	case 7: result.append(1u, a[level][1]);
    			result.append(2u, a[level][0]);
    			break;
    	case 8: result.append(1u, a[level][1]);
    			result.append(3u, a[level][0]);
    			break;
    
    	case 9: result.append(1u, a[level][0]);
    			result.append(1u, a[level+1][0]);
    			break;
    	}
    
    	for (int i = 0; i < 3; i++)
    		delete[] a[i];
    
    	return result;
    }
    string intToRoman(int num) {
    	if (num == 0)	return "";
    
    	string result("");
    	int level = 0;
    	while (num){
    		int digit = num % 10;
    		num /= 10;
    
    		if (level == 3)
    			result = string("").append(digit, 'M') + result;
    		else
    			result = digit2Roman(digit, level) + result;
    		level++;
    	}
    
    	return result;
    
    }
    

    };


Log in to reply
 

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