A 1ms C solution


  • 0
    G
    char* convertToTitle(int n) {
        char *title = malloc(sizeof(char)*16);
        int count = 0;
        int max = 16;
        
        while (n) {
            title[count] = (n-1)%26+ 'A';
            count++;
            if (count > max) {
                title = realloc(title, sizeof(char)*max*2);
                max *= 2;
            }
            n -= 1;
            n /= 26;
        }
        title[count] = 0;
        count--;
    
        for (int i = 0; i <= count/2; i++) {
            char temp = title[i];
            title[i] = title[count - i];
            title[count - i] = temp;
        }
        
        return title;
    }
    

    Allocate a string on the heap to contain our Excel title. While n is greater than 0, we find its corresponding letter in base 26 and stick it onto the string, noting that we're "appending" letters in reverse of what we want. If at any time we need more space, we just reallocate our string.

    Once the string is complete, but backwards, we drop a null terminator, decrement count, and use count as the length of our string. The decrement is useful in the following for loop, which reverses the string but leaves the null terminator where it is. Finally, we return the string.


Log in to reply
 

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