Viky
Viky

Reputation: 63

Conversion of base 10 to base 6

I tried to convert a base 10 number to base 6 in C, but my code didn't pass 2 hidden test cases.

I can't find any logical error in it.

Could you?

//convert base 10 to base 6

#include<stdio.h>
int main()
{
   int num, rem = 0, i = 1, res = 0;
   scanf("%d", &num);
   while(num!=0)
   {
       rem = num%6;
       res = (rem*i)+res;
       num = num/6;
       i = i*10;
   }
   printf("%d",res);

}

Upvotes: 3

Views: 7374

Answers (2)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

Your solution will only work for a limited range of int.

Since base 6 will use more digits than a base 10 number, there will be a point where the base 10 number will generate a base 6 number that will not fit into an int, thus producing an overflow.

See this example.

One solution is to use strings to generate the base 6 number. The number is stored in a character array.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
   const int maxdigits = 26;    /* max number of base 6 digits for a 64 bit int */
   int num=123456789, rem = 0;

   /* handle negative input */
   int tempnum = abs(num);

   int lastpos = maxdigits-1;

   /* initialize array, and initialize array to spaces */
   char res[maxdigits + 1];
   memset(res, ' ', maxdigits);

   /* null terminate */
   res[maxdigits] = 0;

   do 
   {
       rem = tempnum % 6;
       res[lastpos--] = rem + '0'; /* set this element to the character digit */
       tempnum /= 6;
   } while (tempnum > 0);
   printf("%s%s", (num < 0)?"-":"", res + lastpos + 1); /* print starting from the last digit added */
}

Output:

20130035113

Upvotes: 4

chqrlie
chqrlie

Reputation: 144740

Converting a number to a given base should be done as a string.

Here is a simple and generic conversion function:

#include <stdio.h>

char *convert(char *dest, size_t size, int val, int base) {
    static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
    char buf[66];
    char *p = buf + sizeof(buf);
    unsigned int n = val;

    if (base < 2 || base > 36 || !dest || size == 0)
        return NULL;
    if (val < 0)
        val = -n;

    *--p = '\0';
    while (n >= base) {
        *--p = digits[n % base];
        n /= base;
    }
    *--p = digits[n];
    if (val < 0)
        *--p = '-';
    if (buf + sizeof(buf) - p > size) {
        buf[size - 1] = '\0';
        return memset(buf, size - 1, '*');
    } else {
        return memcpy(dest, p, buf + sizeof(buf) - p);
    }
}

int main() {
    char buf[32];
    int num;

    while (scanf("%d", &num)) {
        printf("%d -> %s\n", num, convert(buf, sizeof buf, num, 6);
    }
    return 0;
}

Upvotes: 2

Related Questions