Leetcode 504. Base 7 Solution in C

Having just learnt how to convert decimal numbers to binary by hand a month or two ago, this was right up my alley.

The methods I used were probably not the most concise or elegant, but they are fast and light on RAM, and I have the receipts to prove it!

In order to use as little resources as possible, I didn’t even use strdup.

char* convertToBase7(int num) {
    if (num == 0) {
        // Edge case
        char* s = malloc(2);
        s[0] = '0';
        s[1] = '\0';
        return s;
    }
    // Process negative numbers
    bool neg = (num < 0) ? 1 : 0;
    if (neg) 
        num *= -1;

    // Temporary array for base 7 digits
    int* n7 = malloc(9 * sizeof(int));
    int nLen = 0;

    // Actual conversion
    while (num > 7) {
        n7[nLen] = num % 7;
        num /= 7;
        nLen++;
    }
    if (num == 7) {
        n7[nLen] = 0;
        nLen++;
        n7[nLen] = 1;
        nLen++;
    } else if (num > 0) {
        n7[nLen] = num;
        nLen++;
    }

    // Move digits from int array to char array
    char* s = malloc(nLen + 1 + neg); // Saves memory
    int i = 0;
    int j = nLen - 1;
    nLen += neg;
    if (neg) {
        s[0] = '-';
        i++;
    }
    while (i < nLen) {
        s[i] = n7[j] + '0';
        i++;
        j--;
    }
    s[i] = '\0';

    return s;
}

Posted

in

, , ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *