My stupid C solution, 24ms


  • 0
    L

    //char* intToRoman(int num) {

    int index[13] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    //char* roman[13] = {'M', "CM", 'D', "CD", 'C', "XC", 'L', "XL", 'X', "IX", 'V', "IV", 'I'};
    int charNum[13] = {1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1};
    int cnt[13];
    
    int len = 0;
    int i , j , k;
    for(i = 0 ; i < 13 ; i++){
        cnt[i] = num / index[i];
        len += charNum[i] * cnt[i];
        num = num % index[i];
    }
    
    char* res = (char*)malloc(sizeof(char *) * len);
    j = 0;
    for( i = 0; i < 13; i++){
        switch(i){
            case 0 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'M'; j++;} break;  //'char* res' must be added one by one!
            case 1 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'C'; res[j+1] = 'M'; j+=2;} break;
            case 2 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'D'; j++;} break;
            case 3 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'C'; res[j+1] = 'D'; j+=2;} break;
            case 4 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'C'; j++;} break;
            case 5 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'X'; res[j+1] = 'C'; j+=2;} break;
            case 6 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'L'; j++;} break;
            case 7 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'X'; res[j+1] = 'L'; j+=2;} break;
            case 8 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'X'; j++;} break;
            case 9 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'I'; res[j+1] = 'X'; j+=2;} break;
            case 10 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'V'; j++;} break;
            case 11 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'I'; res[j+1] = 'V'; j+=2;} break;
            case 12 : for(k = 0; k < cnt[i] ; k++) {res[j] = 'I'; j++;} break;
        }
    }
    res[j] = '\0';
    return res;   
    

    }


Log in to reply
 

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