Problem of the Day
A new programming or logic puzzle every Mon-Fri

Base 62

Today's problem is as simple as it sounds. Create a function that converts an integer in to base 62. Your character set is [a-zA-Z0-9].

Permalink: http://problemotd.com/problem/base-62/

Comments:

  • Anonymous - 9 years, 3 months ago

    Quick and Dirty C Solution.

    void reverse_str(char *str, int len) {
        for(int i = 0; i < len/2; ++i) {
            str[len] = str[i]; 
            str[i] = str[len-1-i];
            str[len-1-i] = str[len];
        }
        str[len] = '\0';
    }
    
    void base62(int number) {
        char buffer[256];
        int base = 62;
        int next = number;
        int current = 0;
        int buffer_index = 0;
    
        char tmp = '!';
    
    
        while(next > 0) {
            current = next % base;
    
            if(current < 10) {
                tmp = '0' + current;
            } else if(current < 10+26) {
                tmp = 'a' + (current - 10);
            } else {
                tmp = 'A' + (current - (10+26));
            }
    
            buffer[buffer_index] = tmp;
    
            next = next / base;
            buffer_index++;
        }
    
        buffer[buffer_index] = '\0';
    
        reverse_str(buffer, buffer_index);
    
        printf("Number %d ->  %s\n", number, buffer);
    
    }
    
    int main(void) {    
    
        base62(0);
        base62(10);
        base62(35);
        base62(36);
        base62(61);
        base62(62);
        base62(63);
        base62(1838737);
    
        return 0;
    }
    

    reply permalink

  • David - 9 years, 2 months ago

    Looks like you coded this problem up in the file you used for reverse string. ;)

    reply permalink

Content curated by @MaxBurstein