leetcode 12 整数转罗马数字

自己的写法

这里遇到一个问题就是strcat函数,带来的问题strcat的第一个参数必须要有足够的空间来存放字符,所以我使用malloc时*16,来保证空间足够。

char * intToRoman(int num){
    char *st[] = {"I","II","III","IV","V","VI","VII","VIII","IX"};
    char *st2[]= {"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
    char *st3[] = {"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
    char *st4[] = {"M","MM","MMM"};
    int i,n;
    char *st5[4] = {"0","0","0","0"};
    for(i=0;i<4;i++){
        n = num % 10;
        num /= 10;
        if(i == 0){
            if(n>0){
                st5[3] = st[n-1];
            }

        }
        if(i==1){
            if(n>0){
                st5[2] = st2[n-1];
            }
        }
        if(i == 2){
            if(n > 0){
                st5[1] = st3[n-1];
            }
        }
        if(i == 3){
            if(n>0){
                st5[0] = st4[n-1];
            }
        }

    }
    
    char* s = malloc(sizeof(char) * 16);
    s[0] = '\0';
    for(i=0;i<4;i++){
        if(st5[i] != "0"){
            strncat(s,st5[i],20);
		}
    }

	
  

    return s ;
}

官方的写法,写的挺好

const int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
const char* symbols[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

char* intToRoman(int num) {
    char* roman = malloc(sizeof(char) * 16);
    roman[0] = '\0';
    for (int i = 0; i < 13; i++) {
        while (num >= values[i]) {
            //下面是非常机智的做法,
            num -= values[i];
            strcpy(roman + strlen(roman), symbols[i]);
        }
        if (num == 0) {
            break;
        }
    }
    return roman;
}

leetcode 12 整数转罗马数字_第1张图片

 官方就是用的贪心法则来解题的。

你可能感兴趣的:(LeetCode,leetcode,算法)