Leetcode-12整数转罗马数字

开始我以为不能用strcat这个函数,还另外写了这个函数。

C版本,我感觉C语言写涉及到字符串的东西就很麻烦。

int getLength(int num)
{
    int i = 0;
    while(num)
    {
        i++;
        num = num /10;
    }
    return i;
}


char *getChar1(int num, char *a) {
    char *singleRoman =  (char*)(malloc(sizeof(char)*num*3));
    int len =  strlen(a);
     for(int i = 0; i<3*num; i++)
    {
        singleRoman[i] = 0;
    }
    for(int i = 0; i < num*len ; i++)
    {
        singleRoman[i] = a[i%len];
    }
    return singleRoman;
}
char *getChar2(int num, char a) {
    char *singleRoman =  (char*)(malloc(sizeof(char)*num*3));
    for(int i = 0; i<3*num; i++)
    {
        singleRoman[i] = 0;
    }
    
    for(int i = 0; i < num; i++)
    {
        singleRoman[i] = a;
    }
    return singleRoman;
}


char *strCatch(char *c1, char *c2) {
    int len =  strlen(c1)+strlen(c2);
    char *c3 = (char*)(malloc(sizeof(char)*len));
    for(int i = 0; i

再看看别人写的比较好懂的,真的是留下了没技术的泪水。

char* intToRoman(int num) {
    	int base[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
	char *str[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX",
		"V", "IV", "I" };
	char *roman = (char*)malloc(sizeof(char) * 20);
 
	roman[0] = '\0';
	int i = 0;		
	while (num != 0) 	
	{
		if (num >= base[i]) 
		{
			num -= base[i];
			strcat(roman, str[i]);
		}
		else
			i++;				 
	}
	return roman;	

}

C++版本和这个C版本差不多。

class Solution {
public:
    string intToRoman(int num) {
        string res = "";
        vector val{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        vector str{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        for (int i = 0; i < val.size(); ++i) {
            while (num >= val[i]) {
                num -= val[i];
                res += str[i];
            }
        }
        return res;
    }
};

 

你可能感兴趣的:(LeetCode)