My C solution


  • 0
    S
    int append(char* str, int num, int index) {
        if(num == 0) {
            *(str + index) = '0';
            return index + 1;
        }
        int res = index;
        while(num != 0) {
            *(str + index++) = (char)('0' + (num % 10));
            num /= 10;
        }
        int temp = index - 1;
        while(temp > res) {
            *(str + temp) ^= *(str + res);
            *(str + res) ^= *(str + temp);
            *(str + temp--) ^= *(str + res++);
        }
        return index;
    }
    
    char* countAndSay(int n) {
        if(n == 1) return "1";
        char *pre_str = countAndSay(n - 1);
        int len = strlen(pre_str);
        char* str = calloc(2 * len + 1, sizeof(char));
        int index = 1, count = 1, new_index = 0;
        int cur, pre;
        pre = *pre_str;
        while((cur = *(pre_str + index++)) != '\0') {
            if(cur == pre) {
                count++;
            } else {
                new_index = append(str, count, new_index);
                new_index = append(str, pre - '0', new_index);
                count = 1;
            }
            pre = cur;
        }
        new_index = append(str, count, new_index);
        new_index = append(str, pre - '0', new_index);
        *(str + new_index) = '\0';
        return str;
    
    }
    
    

Log in to reply
 

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